2

I have the code below:

$(document).ready(function(){

  var counter = 0;

  $("button").click(function() {
    $('body').append("<button>generate new element "+(counter++)+"</button>")
  });

});

JSFiddle

When you click duplicated button, it won't duplicate another button again besides the original button only works.

Why cannot listen this event to duplicated buttons?

EDITED:

//Click button event DELEGATION
$(document).on("click",".choice", function() {
  var userChoice = $(this).attr("value");
  //EXTERNAL SPAGUETTHI CODE
};

Need to grab "value" of this button when it's clicked.

GAntoine
  • 1,265
  • 2
  • 16
  • 28
Ivan
  • 1,221
  • 2
  • 21
  • 43

1 Answers1

2

You need delegation: catching the clicks on the parent but only those that were made on button elements. $("button") selects the existing buttons on the page, $(document) (you can replace document with your button container) will select the container and by using $(document).click("button", ...) you delegate the clicks on the buttons.

$(document).ready(function() {
  var counter = 0;

  $(document).click("button", function(e) {
    var value = $(e.target).attr("data-value"); // or .data("value")
    alert(value);
    $('body').append("<button data-value=\"" + ++counter + "\">generate new element " + counter + "</button>")
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-value="initial-button">generate new element</button>

Here are some other similar answers I posted:

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • Do you have some alternatives of this snippet? It forces to click a button without user input after of ajax content. – Ivan Feb 21 '16 at 04:35
  • @Ivan What do you mean by *It forces to click a button without user input,*? By doing `click("button", fn)` you **append** a click handler, you do NOT click the button. To click the button you use `$("button").click()`. – Ionică Bizău Feb 21 '16 at 04:36
  • I was going to use $(this); do you know how to select "button" instead of "document"? – Ivan Feb 21 '16 at 04:43
  • @Ivan It's not clear to me what do you want to achieve—you said you want to catch the clicks on the new buttons. Isn't handling clicks on new buttons what you wanted? – Ionică Bizău Feb 21 '16 at 04:48
  • I looked up about on(); it worked me but I need to know how to fix for $(this).attr; Updating my question, this comment cannot format code. – Ivan Feb 21 '16 at 04:50
  • Done, can you check my edited question? I dont bother you anymore and I will accept your answer after of clearing my doubt, thanks. – Ivan Feb 21 '16 at 04:52
  • @Ivan Ah, you have to use `event.target` instead of `this`. Because `this` will be the `document`/container. :) – Ionică Bizău Feb 21 '16 at 05:00