Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery- store id of clicked link in variable

This should be basic, but for some reason its not working for me. I just want to store the id when a link that has a certain class is clicked in a variable so as an example:

<a href="#" id="this_id_here" class="only_this_class">Some link</a>

I would want jquery to get the id of the link above and store it in a variable. I have tried $this.attr("id") and $this.id, but non of this worked.

This is what I have for the jquery:

  $(".only_this_class").click(function() {

      var clickedId= $(this).attr("id");
      alert(clickedId);
   });

I just get "undefined" every time.

like image 359
cbr0wn Avatar asked Aug 28 '11 00:08

cbr0wn


2 Answers

I removed the space between this and _class in class="only_this _class" and it is working for me.

Try this here

Please have a look at jQuery Selectors

If you have two classes in your HTML then the syntax is different:

$('.classA.classB')

Have a look at How can I select an element with multiple classes?

like image 162
Naveed Avatar answered Nov 15 '22 22:11

Naveed


NAVEED is right, if you remove the space it works, because if there is a space HTML will put two classes on the element: only_this and _class.

If you are in fact looking for two different classes, you should replace the space with a dot to make it work properly, as in $(".only_this._class")

like image 3
gengkev Avatar answered Nov 15 '22 20:11

gengkev