Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: how to get the value of id attribute?

Tags:

jquery

Basic jquery question. I have an option element as below.

<option class='select_continent' value='7'>Antarctica</option>   

jquery

$(".select_continent").click(function () {   alert(this.attr('value')); }); 

This gives an error saying this.attr is not a function so im not using "this" correctly.

How can i get it to alert 7?

like image 252
stef Avatar asked Oct 24 '09 15:10

stef


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 can get li id value in jQuery?

on('click', function (e) { var id = $(e. target). attr('id'); console. log(id); });

How get data attribute in jQuery?

To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).

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.


2 Answers

You need to do:

alert($(this).attr('value')); 
like image 133
danjarvis Avatar answered Sep 19 '22 10:09

danjarvis


To match the title of this question, the value of the id attribute is:

var myId = $(this).attr('id'); alert( myId ); 

BUT, of course, the element must already have the id element defined, as:

<option id="opt7" class='select_continent' value='7'>Antarctica</option> 

In the OP post, this was not the case.


IMPORTANT:

Note that plain js is faster (in this case):

var myId = this.id alert(  myId  ); 

That is, if you are just storing the returned text into a variable as in the above example. No need for jQuery's wonderfulness here.

like image 23
cssyphus Avatar answered Sep 21 '22 10:09

cssyphus