Search code examples
jqueryevent-delegation

jQuery Event Delegation for text input on change


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.


Solution

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