4

I'm trying to add a data-name attribute on clicking one element and then when that element is clicked do something else.

$(".btn01").on("click", function() {
    $(".next").attr("data-name", "btn02");
});

$("[data-name='btn02']").on("click", function() {
    console.log("I clicked this button");
});

It is updating in the DOM but not working? Any ideas?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
alib0ng0
  • 459
  • 1
  • 5
  • 15

3 Answers3

2

You must use event delegation since the attribute you're using in the selector of the second click event [data-name='btn02'] is created dynamically by the JS code:

$(".btn01").on("click", function() {
  $(".next").attr("data-name", "btn02");
});

$("body").on("click", "[data-name='btn02']", function() {
  console.log("I clicked this button");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn01">CLICK ME then click the span bellow</button>
<br><br>
<span class="next">Next span</span>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
1

Try the following, use event delegation for attaching event to "[data-name='btn02']", as $("[data-name='btn02']") element will not exist till $(".btn01") is clicked.

$(".btn01").on("click", function() {
  $(".next").attr("data-name", "btn02");
});

$(document).on("click", "[data-name='btn02']", function() {
  console.log("I clicked this button");
});
Rohit Garg
  • 782
  • 5
  • 18
-1

If you are just trying to make it so the first button needs to be clicked before the second can, you can just use a boolean variable for that:

var firstButtonClicked = false;
$(".btn01").on("click", function() {
    firstButtonClicked = true;    
});
// the second button
$(".next").on("click", function() {
    if (firstButtonClicked == true) {
        console.log("I clicked this button after the first one");
    }
});