bitee
bitee

Reputation: 47

How to get all attr value in same class by click() jQuery

I am making a Simon game, but I need to get the "id" (attribute) value. but whenever I click on the different color it still gives me the first attr value which is in this case is green. how many times do I click on the red, blue, or yellow button but it still gives me a green value (the first one). help, please!

//Below code HTML

<div class="container">
      <button class="btn green" id="green"></button>
      <button class="btn red" id="red"></button><br />
      <button class="btn yellow" id="yellow"></button>
      <button class="btn blue" id="blue"></button>
    </div>

//Below code Jquery

$(".btn").click(function () {
    var userChosenColor =$(".btn").attr("id");
    console.log(userChosenColor);
});

Upvotes: 0

Views: 1199

Answers (1)

prettyInPink
prettyInPink

Reputation: 3419

Reference to the button clicked. You do not necessarily need jQuery for this.

$(".btn").click(function () {
    var userChosenColor = $(this).attr("id");
    console.log('jQuery: '+ userChosenColor);
});

/* non jQuery */
const btns = document.querySelectorAll('.btn');

btns.forEach(btn=> {
  btn.addEventListener('click', () => {
    console.log('JS only: '+btn.id)
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <button class="btn green" id="green">1</button>
  <button class="btn red" id="red">2</button><br />
  <button class="btn yellow" id="yellow">3</button>
  <button class="btn blue" id="blue">4</button>
</div>

Upvotes: 1

Related Questions