Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ID of a Clicked Link

In the code below and demo here http://jsfiddle.net/jasondavis/vp2YN/3/ you can see I need to get the ID attribute of a clicked item and assign it to a variable in Javascript.

Right now the code returns the ID name of the first item, regardless of which item is clicked on.

In the Javascript you can see I have this line commented out...

var clickedID = this.attr("id"); when I use that line, I get an error saying: Object has no method 'attr'

Please help me get the ID name of the clicked link and assign it to a variable

HTML

<a href="#" style="display:block" class="button insertcolumn" id="one_half">2 Columns</a>

<a href="#" style="display:block" class="button insertcolumn" id="one_third">3 Columns</a>

<a href="#" style="display:block" class="button insertcolumn" id="one_fourth">4 Columns</a>​

Javascript/jQuery

jQuery('.insertcolumn').click(function(){

    var clickedID = jQuery('.insertcolumn').attr("id");
    //var clickedID = this.attr("id");

    alert(clickedID);

});​

Demo http://jsfiddle.net/jasondavis/vp2YN/3/

like image 938
JasonDavis Avatar asked Sep 15 '12 20:09

JasonDavis


People also ask

How do you get a clicked item 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 can I get the text value of a clicked link?

Answer: Use the jQuery . attr() Method attr() method to dynamically set or change the value of href attribute of a link or anchor tag. This method can also be used to get the value of any attribute.

How do I get a click URL?

Answer: Use the window. location. href Property You can use the JavaScript window. location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc. The following example will display the current url of the page on click of the button.


1 Answers

You have to reference the one you clicked with the jQuery wrapper!

You want to use

$(this).attr('id');

To get the id (without traversing the DOM for no reason) you would be better off to just call the object id.

this.id; 

But to access the property regardless of the type of attribute and depending on the name of the attribute use the following code.

jQuery('.insertcolumn').click(function(){

    var clickedID = $(this).attr('id');


    alert(clickedID);

});​
like image 67
Zevi Sternlicht Avatar answered Oct 18 '22 00:10

Zevi Sternlicht