-1

I'm creating buttons based on what a user enters into an input box. However, the function i have linked to the dynamically created buttons won't fire when pressed.

function btnCreate() {
num++;
userBtn = $("<button>")
userBtn
    .addClass("btn search-term-btn dynamicElement")
    .appendTo($(".btn-holder"))
    .text(topics)
    .attr("data-name", topics);
usedTopics.push(topics + num);
topics = [];
console.log(num);
};

$(".search-term-btn").on("click", ".dynamicElement", function () {
// takes the name of the button 
searchValue = $(".search-term").attr("data-name");
console.log(searchValue);
})

The class is correct, ive checked with the inspector. I just can't seem to figure out why it's unresponsive

tn97
  • 3
  • 4
  • Are you creating buttons inside buttons? – Teemu Sep 13 '18 at 09:21
  • You need to provide a [mcve] – Quentin Sep 13 '18 at 09:22
  • No, im using the input submit button to call a function that causes the buttons to be made – tn97 Sep 13 '18 at 09:22
  • Then you probably submit the form, and your server sends a new page as a response. As Quentin said, please post a reproducable example, so that we don't have to speculate. – Teemu Sep 13 '18 at 09:23
  • Possible duplicate of [Jquery how to bind click event on dynamically created elements?](https://stackoverflow.com/questions/17558167/jquery-how-to-bind-click-event-on-dynamically-created-elements) – Pete Sep 13 '18 at 09:32
  • You append the newly created buttons to `.btn-holder`. does that element also have the `.search-term-btn` class? Is it a child of `.search-term-btn` Or is it a different element with a handler not shown? As written, it comes across as if the buttons aren't appended to the container that has the delegated event handler. – Shilly Sep 13 '18 at 09:36

2 Answers2

1

Create the click event on DOM.

$(document).on("click", ".search-term-btn .dynamicElement", function () {
   console.log(this)
});
Roy Bogado
  • 4,299
  • 1
  • 15
  • 31
  • oh my god, that solved it.. thank you. Ive been looking back to some activity works and none of them have used this. But this seems to have fixed it. Thank you very much! – tn97 Sep 13 '18 at 09:27
0
while you are creating the buttons, you can add the onclick function there..
like userBtn = $("<button onlcikc="somefunction(this)">")

OR you can use on function which is

$('body').on(  "click",".dynamicElement", function() {  
  //your code
}); 
pixellab
  • 588
  • 3
  • 12
  • delegate has been deprecated in jquery 3, you should use .on() instead – Pete Sep 13 '18 at 09:31
  • Yes like $(document).on("click", 'p',function() { $(this ).after( "

    Click me for another paragraph.

    " ); });
    – pixellab Sep 13 '18 at 09:34
  • Still second one won't work as .dynamicElement is created after the document is loaded. – tmw Sep 13 '18 at 09:41