Вопрос

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.

Это было полезно?

Решение 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'));
});

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top