jQuery Event Delegation for text input on change

4.9k views Asked by At

I'm trying to attach an on change event to an input that I insert dynamically. The HMTL starts out like this:

<div id="myDiv"></div>

Then get HTML injected into it when the page is active (it loads via ajax so instead of onReady it uses the success function):

$("#myDiv").html('<table><tr><td><input type="text" class="myInput"></td></tr></table>');

in order to attach an onChange event handler to this, I have the following event delegation event binding in the onReady of the doc:

$("#myDiv").on('change', 'input.myInput', function(){ alert($(this).attr('id')); })

Is there something I'm doing wrong, the event never gets triggered.

3

There are 3 answers

1
E. S. On BEST ANSWER
$("body").on('change', '.myinput', function(){ alert($(this).attr('id')); });

Try this: http://jsfiddle.net/h7wyS/ .

$("#myDiv").html('<table><tr><td><input type="text" class="myInput"> </td></tr></table>');

// added the 'blur' too.
$("#myDiv .myInput").on('change, blur', function(e){ 
    alert($(this).parents('div:first').attr('id'));
});
0
tymeJV On

Javascript is case-sensitive, your class name is myinput, but you're listening on myInput, change one or the other.

0
Praishgm On

Couple of thinks to notice, you are using camel case in second line which should actually be 'myinput'. And this element doesn't have Id so you might wanna add id, else you get undefined in alert box.