0

On my HTML I have buttons list and text input field. Input field is to add extra buttons to my buttons list.

On jQuery I have eventListener when one of these buttons with .choices is clicked console log its value.

It works fine without any errors. But when I add extra button to my list with same class (.choices) new button appears but it doesn't respond to my click.

Any suggestions?

<div class="buttons">
  <button id="button0" class="choices">Running</button>
  <button id="button1" class="choices">Yoga</button>
  <button id="button2" class="choices">Karate</button> 
</div>

JS

$("#add-button").click(function(){
  var inputValue = $("#add-input").val();
  var generatedId = "button" + healthyChoices.length;
  healthyChoices.push(inputValue);
  $("<button>").attr("id", generatedId).appendTo(".buttons");
  $("#" + generatedId).attr("value", inputValue);
  $("#" + generatedId).attr("class", "choices");
  $("#" + generatedId).text(inputValue);
  $("#add-input").val("");
});


$(".choices").click(function(){
  var selectedGroup = $(this).val();
  console.log(selectedGroup);
});
  • 3
    `$(".buttons").on('click', '.choices', function() {` – dfsq Jan 03 '19 at 21:56
  • The comment @dfsq posted is how I'd do it, but I'd suggest further that they make it an answer with an explanation as to why that binds the event differently than what the OP posted. for points. =) – Nikki9696 Jan 03 '19 at 21:59
  • If you do this: `newbutton = $(" – Diodeus - James MacFarlane Jan 03 '19 at 22:02
  • 3
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Taplar Jan 03 '19 at 22:05
  • For performance reasons, I would advise you to avoid `$("#" + generatedId).method()` calls repeatedly like you are doing. `var $newButton = $(' – Taplar Jan 03 '19 at 22:06
  • Something such as: https://jsfiddle.net/63dbt0ye/ – Taplar Jan 03 '19 at 22:11

1 Answers1

0

The .click method does not handle elements dynamically added to the DOM. You should be using the .on method (as indicated by dfsq's comment).

See this SO post: Difference between .on('click') vs .click()

Sean Murphy
  • 516
  • 4
  • 7