Question

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.

Was it helpful?

Solution 2

$("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'));
});

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top