Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get id of element on button click using jquery

Tags:

jquery

i have list of dynamic generated buttons and id is generated on run time. how can is get id of clicked button using JQuery.

Here is js code

var btn = " <input type='button' id='btnDel' value='Delete' />";


$("#metainfo").append(txt); //set value of

$("#btnDel").attr("id", "btnDel" + $("#hid").attr("value")); 
like image 907
Xulfee Avatar asked May 19 '10 09:05

Xulfee


People also ask

How do I get the ID of clicked element?

One of the ways to get an ID attribute of a clicked element is that you actually attach click events to all the buttons inside For loop. Get DOM references to all the buttons by invoking getElementsByTagName() on the document object with an argument button.

How do I get the ID of a button clicked in react?

To get the id of the element on click in React: Set the onClick prop on the element to a function. Access the id of the element on the currentTarget property of the event . For example, event.currentTarget.id returns the element's id .


1 Answers

For your example it would be like this:

$("#btnDel").click(function() {
  alert(this.id);
});

Note that you can't loop the code you have, IDs have to be unique, you'll get all sorts of side-effects if they're not, as it's invalid HTML. If you wanted a click handler for any input, change the selector, like this:

$("input").click(function() {
  alert(this.id);
});
like image 50
Nick Craver Avatar answered Oct 01 '22 19:10

Nick Craver