Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the jQuery `$(this)` id?

How can I get the id of the element that triggered the jQuery .change() function? The function itself works properly, but I need a specific action for a selector with id="next".

$("select").change(function() {     [...snip....]     alert( $(this).attr('id') );  // <---- not working } 

Any ideas why the alert above isn't working?

like image 642
Gigg Avatar asked Jun 14 '11 15:06

Gigg


People also ask

How can I get the id of an element using jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do I know which id is clicked in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element. The following example will display the ID of the DIV element in an alert box on button click.

Can I use id in jQuery?

id is not a valid jquery function. You need to use the . attr() function to access attributes an element possesses.

What is id * in jQuery?

This is the most generous of the jQuery attribute selectors that match against a value. It will select an element if the selector's string appears anywhere within the element's attribute value.


2 Answers

this is the DOM element on which the event was hooked. this.id is its ID. No need to wrap it in a jQuery instance to get it, the id property reflects the attribute reliably on all browsers.

$("select").change(function() {         alert("Changed: " + this.id); } 

Live example

You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event object's target property:

$("#container").change(function(event) {     alert("Field " + event.target.id + " changed"); }); 

Live example

(jQuery ensures that the change event bubbles, even on IE where it doesn't natively.)

like image 173
T.J. Crowder Avatar answered Sep 20 '22 14:09

T.J. Crowder


Do you mean that for a select element with an id of "next" you need to perform some specific script?

$("#next").change(function(){     //enter code here }); 
like image 34
John Kalberer Avatar answered Sep 20 '22 14:09

John Kalberer