2

SO,

My question is fairly simple I guess. I provided a small code snippet to help illustrate the problem.

I'm trying to grab the button's id. It works fine unless you click one any of the text inside the button, then the jQuery tries to grab that instead.

I am using event.target.attributes.id.value to locate the id attribute of the clicked element, but if anyone knows a simpler way by all means please share this!

If you need help understanding the problem, just run the code snip and attempt clicking on the button, then on the text inside the button. The console log statement should show the id of the button clicked no matter what.

Thank you to anyone who can help.

$(document).on("click", ".eat", event => {
        event.preventDefault();
        const id = parseInt(event.target.attributes.id.value);
        console.log(id); 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-success eat" id="10">
<p>What is my ID?</p>
<h4>---> Click to find out! ---></h4>
</button>
<button type="button" class="btn btn-success eat" id="11">
<p>What is my ID?</p>
<h4>---> Click to find out! ---></h4>
</button>
JSONaLeo
  • 416
  • 6
  • 11
  • 2
    Possible duplicate of [Getting the ID of the element that fired an event](https://stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event) – Lowkey Feb 15 '18 at 02:16

2 Answers2

2

A pretty simple and clear solution is:

$(".eat").click(function(e) {
    e.preventDefault();
    console.log($(this).attr("id"));
})

Then you can parseInt that id.

Dencio
  • 518
  • 3
  • 12
  • Thanks that works! I actually think the ES6 arrow syntax I was using may have had some part in causing the problem. – JSONaLeo Feb 15 '18 at 02:40
1

I would solve your question problem using a little more jQuery but in fact easier. Just by taking each button and adding an event to each .

Hope this is what you were looking for. Happy to explain or help in a better solution if needed.

$('.eat').each(function(){
      $(this).click(function(){
        var id = $(this).attr('id');
        console.log(id);
      })
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" class="btn btn-success eat" id="10">
<p>What is my ID?</p>
<h4>---> Click to find out! ---></h4>
</button>

<button type="button" class="btn btn-success eat" id="11">
<p>What is my ID?</p>
<h4>---> Click to find out! ---></h4>
</button>
Gerardo BLANCO
  • 5,590
  • 1
  • 16
  • 35
  • The problem here is that I have other buttons on the page so I can't just use a universal buttons selector. I only want to do this with the buttons with the class "eat". Also I'm dynamically generating these buttons with the new id's so I think I need to use $(document).on('click'... – JSONaLeo Feb 15 '18 at 02:33
  • Instead of targeting the button, we can target the calss ``eat`` – Gerardo BLANCO Feb 15 '18 at 03:05