shajin
shajin

Reputation: 3264

Dynamically generated Dropdown not listening to jquery event

$(document).ready(function() {
    $('[id^=drop_id]').on('change', function() {
        selected = $(this).find('option:selected').data('tid')   
        $.getJSON('path/'+selected,function(data){
        var s = $("<select id='drop_id_goddamnit' name=\"name\" />");
        $(data).each(function() {
          var option = $('<option />');
          option.attr('value', this.taxon.permalink).text(this.taxon.name).attr('data-tid',this.taxon.id);
          option.appendTo(s);
        });
        $('#header').append($(s));
    });
  });
});

I've this code.This will add a dropdown according to an existing dropdown's selected value.And also the newly created dropdown has the same change event to generate another dropdown.But the dynamically generated Select box is not firing up the event.

What to do?

Upvotes: 2

Views: 1282

Answers (3)

Jai
Jai

Reputation: 74738

Its a case of event delegation, newly created elems will not get the change event, try this way:

$(document).on('change', '[id^="drop_id"]', function(){
    //your corresponding code.
});

Because when document was loaded the element was not there in the dom so direct event binding will not affect to the newly inserted dom elem. That's why we need to delegate the event to the either $(document) which is the parent of all other elems or the closest existing parent which was available when dom loaded.

so the final code should look like this:

$(document).on('change', '[id^="drop_id"]', function() {
    selected = $(this).find('option:selected').data('tid')   
    $.getJSON('path/'+selected,function(data){
    var s = $("<select id='drop_id_goddamnit' name=\"name\" />");
    $(data).each(function() {
      var option = $('<option />');
      option.attr('value', this.taxon.permalink).text(this.taxon.name).attr('data-tid',this.taxon.id);
      option.appendTo(s);
    });
    $('#header').append($(s));
});

Upvotes: 5

Techie
Techie

Reputation: 45124

Your code should change as below. Bind the event to an existing element in the DOM. Then look for the child elements. You should do some reading on event delegation using .on method.

As of jQuery 1.7, .delegate() has been superseded by the .on() method. For earlier versions, however, it remains the most effective means to use event delegation. More information on event binding and delegation is in the .on() method.

Replace $('[id^=drop_id]').on('change', function() { With below

 $('#parentid').on('change', '[id^=drop_id]', function() {

The problem with your code is that newly added elements do not have the event bound to them.

Read more

Upvotes: 1

Leon
Leon

Reputation: 12481

Nowhere is the onchange event bound for this new drop down. The only onchange binding is happening on page ready. You must explicitly bind the onchange to the new dropdown aafter it is added to the page

Upvotes: 0

Related Questions