Home > OS >  Firing a click event on a button when the event is added to all buttons to reveal the clicked button
Firing a click event on a button when the event is added to all buttons to reveal the clicked button

Time:09-11

I added the click event to all buttons but my intention is to have the event occur on a button inorder to extract the buttons text(btnText).

I have tried the .removeClass() and .addClass() methods but its still not working as I expected.

<ul>
  <li><button>Dog</button></li>
  <li><button>Cat</button></li>
  <li><button>Moose</button></li>
</ul>
$('button').click(() => {
        $('button').removeClass("selected");
        $(this).addClass("selected");
        let btnText = $(this).text(); *// expected result(Dog|Cat|Moose)*
        console.log(btnText); *// printed result (DogCatMoose)*
}); // end click

CodePudding user response:

That's because of the arrow function which makes this refer to the outer scope which this is window, you need to use function declaration instead to make this refers to the clicked button.

$('button').click(function () {
        $('button').removeClass("selected");
        $(this).addClass("selected");
        let btnText = $(this).text(); // expected result(Dog|Cat|Moose)*
        console.log(btnText); // printed result (DogCatMoose)*
}); // end click
.selected {
  background-color: red;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li><button>Dog</button></li>
  <li><button>Cat</button></li>
  <li><button>Moose</button></li>
</ul>

  • Related