0

Goal:
Show the button "Candy Candy candy" after pressing the button text "Test2"

Problem:
It doesn't show the text and what part am I missing in order to complete it?

I have tried using on() and live() but it still doesn't work.

Info:
*I'm using jQuery and its ajax

Thank you!

$('#test1').click(function() {
  document.getElementById("data1").innerHTML = "<button id='test2' type='button'>Test 2</button>";
});

$('#test2').click(function() {
  document.getElementById("data2").innerHTML = "Candy candy candy !";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
  <button id="test1" type="button">Test 1</button>
  <br/>
  <br/>
  <div id="data1"></div>
  <br/>
  <br/>
  <div id="data2"></div>
</body>

</html>
Zakaria Acharki
  • 63,488
  • 15
  • 64
  • 88
What'sUP
  • 12,102
  • 23
  • 71
  • 120
  • The `#test2` element doesn't exist at the point you attempt to bind the click event handler to it. You need to use a delegated event handler. I'd also suggest you use jQuery methods as you've already loaded it anyway, eg. `$('#data1').html('');` – Rory McCrossan Aug 29 '18 at 15:03
  • Are you sure you want to include jQuery twice in two different versions? – connexo Aug 29 '18 at 15:27

1 Answers1

1

You should use event delegation on() since the button was added automatically after the first click :

$('#test1').click(function() {
  document.getElementById("data1").innerHTML = "<button id='test2' type='button'>Test 2</button>";
});

$('body').on('click', '#test2', function() {
  document.getElementById("data2").innerHTML = "Candy candy candy !";
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
  <button id="test1" type="button">Test 1</button>
  <br/>
  <br/>
  <div id="data1"></div>
  <br/>
  <br/>
  <div id="data2"></div>
</body>
</html>
Zakaria Acharki
  • 63,488
  • 15
  • 64
  • 88