I have the following html tag
<input type="text" id="txtColor" />
<div id="wrapper">
<div id="someDynamicElement"></div>
</div>
When i do this it works
$('#txtColor').live('change',function(){
var x = this.value;
$('#someDynamicElement').css('color',x);
});
But when i try to do the same using on() instead of live() as in the below code, it doesn't work. What am i doing wrong
$('#wrapper').on('change','#txtColor',function(){
var x = this.value;
$('#someDynamicElement').css('color',x);
});
Where #someDynamicElement is an element that is dynamically added to the page.
The reason it's not working is that when you change from live() to on() you need to change the element you set the listener on to the document element. Try this:
$(document).on('change','#txtColor',function(){
console.log($(this).val());
});
You may be calling the code when the element with wrapper ID is not accessible (eg. you do not wait for the DOM to be ready).
Try solving this like that:
$(function(){
$('#wrapper').on('change','#txtColor',function(){
var x = this.value;
$('#someDynamicElement').css('color',x);
});
});
It will attach change event handler to the #wrapper element when the DOM is ready.
Other possibilities (some of which others mentioned):
#txtColor is not within #wrapper,#wrapper is added dynamically,wrapper and txtColor IDs must be unique, meaning they can be assigned to only one element),My guess would be that both #txtColor and #wrapper are dynamically appended to the web-page. So, they are included later, after the jQuery code executes. At the time when that jQuery code executes, there (still) is no #wrapper element on the page...
Did I guess correctly?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With