1

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.

user123_456
  • 5,635
  • 26
  • 84
  • 140

1 Answers1

2

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
}
Moazzam Khan
  • 3,130
  • 2
  • 20
  • 35
  • how would you combine it with this answer: http://stackoverflow.com/questions/14042193/how-to-trigger-an-event-in-input-text-after-i-stop-typing-writting – user123_456 Aug 08 '13 at 08:02
  • 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 – Moazzam Khan Aug 08 '13 at 08:10
  • One more question :) is there any way to send this id and value to the doneTyping() ? – user123_456 Aug 08 '13 at 08:50