-2

I've created buttons with javascript, I've added these to HTML. I want to handle these with jQuery. How to get worked to click on b_1 and b_2?

$("#mainbutton").click(function (){
  document.getElementById("content").innerHTML = '<button id="b_1">Button1</button><button id="b_2">Button2</button>'
})
$("#b_1").click(function (){
  alert("You've clicked button1!");
})

$("#b_2").click(function (){
  alert("You've clicked button2!");
})
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button id="mainbutton">Click me!</button>
<div id="content"></div>
</head>
jhsznrbt
  • 133
  • 1
  • 13
  • 2
    Possible duplicate of [In jQuery, how to attach events to dynamic html elements?](https://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements) – Robin Mackenzie Aug 18 '17 at 12:00

2 Answers2

4

You need to attach the event to the body and select the element in the second argument :)

Edit: I've used body, but it's a better practice to use the closest parent which is static on the page.

$("#mainbutton").click(function (){
  document.getElementById("content").innerHTML = '<button id="b_1">Button1</button><button id="b_2">Button2</button>'
})
$("body").on('click','#b_1',function (){
  alert("You've clicked button1!");
})

$("body").on('click', '#b_2', function (){
  alert("You've clicked button2!");
})
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button id="mainbutton">Click me!</button>
<div id="content"></div>
</head>
johniejohnie
  • 523
  • 2
  • 11
1

since you are adding the buttons dynamically but not attaching event listeners to these buttons when you add them, you need to use event delegation. attach event listeners to #content, something like this:

$("#mainbutton").click(function (){
  document.getElementById("content").innerHTML = '<button id="b_1">Button1</button><button id="b_2">Button2</button>'
})
$("#content").on('click', "#b_1", function (){
  alert("You've clicked button1!");
})

$("#content").on('click', "#b_2", function (){
  alert("You've clicked button2!");
})
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button id="mainbutton">Click me!</button>
<div id="content"></div>
</head>
Dij
  • 9,761
  • 4
  • 18
  • 35