Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find ID of clicked button by class

Tags:

jquery

button

I have numerous buttons on my page with the same class names. However these buttons have different ID's. How do i do this:

$(".vote").click(function(){      var id = $(this).{ID OF CLICKED BUTTON}; }); 

How can i make this pseudo code work?

Thanks

like image 899
benhowdle89 Avatar asked Feb 08 '11 21:02

benhowdle89


People also ask

How do I get the clicked button ID?

To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.

How do I find the button ID of a website?

Chrome: Right-click anywhere on your screen, and click on the Inspect button or press CTRL + SHIFT + I or F12 from your keyboard. Firefox: Right-click anywhere on your screen, and click on the Inspect Element button.

How do I know which button is clicked in HTML?

The Html <button onclick=" "> is an event attribute, which executes a script when the button is clicked. This attribute is supported by all browsers. It is also used to call a function when the button is clicked.

How do you check whether a button is clicked by using Javascript?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.


2 Answers

$(".vote").click(function(){      var id = this.id; }); 

The ID is accessible directly from the element. There's absolutely no need to use a jQuery method.

like image 126
user113716 Avatar answered Oct 15 '22 06:10

user113716


With jQuery object (not necessary)

$(".vote").click(function(){   var id = $(this).attr('id'); }); 


Without jQuery object (faster)

$(".vote").click(function(){   var id = this.id; }); 
like image 25
simshaun Avatar answered Oct 15 '22 08:10

simshaun