1
$\begingroup$

How to have only one keypress event so it can be triggered by any child element in the DOM tree.

For example I have something like this:

<table>
<tr>
  <td><input type="text" id="col_1" value="1"/></td>
</tr>
<tr>
  <td><input type="text" id="col_2" value="2"/></td>
</tr>
<tr>
  <td><input type="text" id="col_3" value="3"/></td>
</tr>
</table>

So for example when user changes the value on id=col_3 and then on id=col_2 how can I distinguish which input triggered this event? I need to be able to save and input id and the value of it in an array so I can read it later on.

$\endgroup$
1
  • $\begingroup$ how are you registering the event handler using jQuery or dom methods $\endgroup$ Commented Aug 8, 2013 at 7:18

1 Answer 1

2
$\begingroup$

You can try using jQuery .on method,

$("table").on("keypress", "input", function(event){
  alert($(this).attr("id"));// gets the input id
  alert($(this).val());// gets the input value
});

This code will take care of all the inputs inside the <table> tag.

If you want not to execute this listener on every keystroke, giving sometime(3 sec) to breath, try this code -

var timeoutReference;

$("table").on("keypress", "input", function(event){
    var el = this; // copy of this object for further usage

    if (timeoutReference) clearTimeout(timeoutReference);
    timeoutReference = setTimeout(function() {
        doneTyping.call(el);
    }, 3000);
});

$("table").on("blur", "input", function(event){
    doneTyping.call(this);
});

function doneTyping(){
    var el = this;
    // we only want to execute if a timer is pending
    if (!timeoutReference){
        return;
    }
    // reset the timeout then continue on with the code
    timeoutReference = null;

    //
    // Code to execute here
    //
    alert('This was executed when the user is done typing.');
    alert($(el).attr("id"));//id
    alert($(el).val());//value
}
$\endgroup$
Sign up to request clarification or add additional context in comments.

3 Comments

how would you combine it with this answer: stackoverflow.com/questions/14042193/…
I can set a timer for it, it depends on, how long you want to wait before you are sure that user has stopped typing, 2 or 3 secs
One more question :) is there any way to send this id and value to the doneTyping() ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.