Vit
Vit

Reputation: 154

How do I target dynamic buttons created with different values jQuery

I have a button where when it's clicked I want the text to change to something else now the problem is that the button has the same class and everything as the other buttons on the page which will be generated dynamically since it's inside a foreach

How can I target only the button I click to change the text I have different values for each button can I use that?

<label class="more-information" value="{I call a data id with php}">
 <span class="more-info-text">Default text</span>
</label>
$('.more-information').on('click', function () {
      $(this).toggleClass('active');
      $(this).hasClass('active') ? $(".more-info-text").text('Default Text') : $(".more-info-text").text('Changed Text');

    });

This is what I'm currently using and it changes the text for all the buttons only when one button is clicked

Upvotes: 1

Views: 141

Answers (1)

Abhilash Augustine
Abhilash Augustine

Reputation: 4208

$('.more-information').on('click', function () {
      $(this).toggleClass('active');
      $(this).hasClass('active') ? $(this).find(".more-info-text").text('Default Text') : $(this).find(".more-info-text").text('Changed Text');

});

$(this).find(".more-info-text") will find the exact label for you on the click.

Upvotes: 1

Related Questions