lad_ruz
lad_ruz

Reputation: 21

jQuery won't work on appended element

HTML:

<fieldset>      
   <select>
      <option value="">Position</option>
   </select>
   <input type="text" />
   <select>
      <option value="">Function</option>
   </select>
   <input type="button" class="buttonAnd" value="And" />
   <input type="button" class="buttonOr" value="Or" />
</fieldset>

jQuery:

$(document).ready(function() {
    field_count = 0;

    $(".buttonAnd").click(function(){
        field_count++;
        $('fieldset').append(jQuery("<br />"));
        var new_field = jQuery("<input type=\"button\" />")
        new_field.attr("class","buttonAnd");
        new_field.attr("name","buttonAnd_"+field_count);
        new_field.attr("value","And_"+field_count);
        $('fieldset').append(new_field);
    });
});

Appending new button works only on original two buttons, but it doesn't work on newly generated buttons. Any idea how to solve this?

Tnx!

Thanx Travis J! I've tried your solution and it works. Thanks to everyone else as well!

Upvotes: 1

Views: 272

Answers (3)

SirDerpington
SirDerpington

Reputation: 11450

You need to use .on() because you create those new buttons "on the fly". So what you need is event delegation. Otherwise the script doesn't notice that there are new buttons

See my fiddle.

$(document).ready(function() {
    field_count = 0;

    $(".buttonAnd").on('click', function(){
        field_count++;
        $('fieldset').append(jQuery("<br />"));
        var new_field = jQuery("<input type=\"button\" />");
        new_field.attr("class","buttonAnd");
        new_field.attr("name","buttonAnd_"+field_count);
        new_field.attr("value","And_"+field_count);
        $('fieldset').append(new_field);
    });
});

Upvotes: 1

pilsetnieks
pilsetnieks

Reputation: 10420

You almost answered your question yourself - that's because the .click() event is assigned to the buttons that exist at the moment when the event is assigned. If you need it to work for newly generated buttons, too, then you have to assign the event to the new buttons after they're created, just take care not to assign it the second time to the original buttons.

Upvotes: 0

Travis J
Travis J

Reputation: 82267

jsFiddle Demo

Use event delegation with jQuery's on. This will allow your future elements to have the event delegated to them

field_count = 0;

$("body").on("click",".buttonAnd",function(){
    field_count++;
    $('fieldset').append(jQuery("<br />"));
    var new_field = jQuery("<input type=\"button\" />")
    new_field.attr("class","buttonAnd");
    new_field.attr("name","buttonAnd_"+field_count);
    new_field.attr("value","And_"+field_count);
    $('fieldset').append(new_field);
});

Upvotes: 2

Related Questions