Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery on() instead of live() not working

Tags:

jquery

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.

like image 995
Pinkie Avatar asked Feb 16 '12 23:02

Pinkie


3 Answers

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());
});
like image 144
Horatio Alderaan Avatar answered Sep 28 '22 04:09

Horatio Alderaan


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,
  • IDs may be duplicated (both wrapper and txtColor IDs must be unique, meaning they can be assigned to only one element),
like image 31
Tadeck Avatar answered Sep 28 '22 05:09

Tadeck


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?

like image 27
Šime Vidas Avatar answered Sep 28 '22 06:09

Šime Vidas