jquery: how to get the value of id attribute?

Jquery

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

You need to do:

alert($(this).attr('value'));

Solution 2 - Jquery

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.

Solution 3 - Jquery

You can also try this way

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

jquery

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

Good luck !!!!

Solution 4 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstefView Question on Stackoverflow
Solution 1 - JquerydanjarvisView Answer on Stackoverflow
Solution 2 - JquerycssyphusView Answer on Stackoverflow
Solution 3 - Jquerysaleem ahmedView Answer on Stackoverflow
Solution 4 - Jquerybillah77View Answer on Stackoverflow