51

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?

4 Answers 4

93

You need to do:

alert($(this).attr('value'));
1
  • 1
    I like @Mottie answer better :) Much simpler! Commented Dec 5, 2015 at 21:41
70

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.

0
5

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 !!!!

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.