Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery doesn't see new elements

I am new to JQuery, so bear with me :).

I have a simple problem:

$(document).ready(function() {

     $("#instrument").change(function() {
         $("#tunings").html("<select id=\"TuningSelector>\"[..]</div>");
     });

     $("#TuningSelector").change(function() {
         DoSomethingWithTheValue();
      }); 

 });

Problem is: When instrument has changed, the script doesn't respond anymore to TuningSelector changes. Like JQuery doesn't see the new TuningSelector element...

Do I need to call a refresh on JQuery or so? So that it sees the refreshed DOM?

like image 623
Peter Avatar asked May 02 '09 15:05

Peter


2 Answers

Generally you want to use on so that it applies the handler to new elements matching the selector and delegate to a higher element in the DOM.

$('body').on( 'change', '#control', function() {
    DoSomething();
});
like image 156
tvanfosson Avatar answered Nov 07 '22 08:11

tvanfosson


With jQuery events if you want the event to apply to new elements you would use the .live method, however jQuery 1.3 doesn't support blur, focus, mouseenter, mouseleave, change, submit events as live events. (change, submit, and blur/focus are on the roadmap for jQuery 1.4)

As an alternative you could use the liveQuery plugin.

like image 41
Sam Hasler Avatar answered Nov 07 '22 08:11

Sam Hasler