Reputation: 51
I am trying to get the "value" attribute in an tag (inside a tag.
My current code:
JavaScript:
var TheId = $('.nameofselect option:selected').val();
HTML:
<option value="123">Text value</option>
But this is returning the "Text value" of the option, not the actual value (i.e. 123) - which is what I need.
Thanks in advance
Upvotes: 1
Views: 170
Reputation: 20418
Use .attr()
selector
Try this
$('.nameofselect option:selected').attr('value'); // Return 123
$('.nameofselect').val() // Return 123
Example HTML
<select class="nameofselect">
<option value="">select</option>
<option value="123">Text value</option>
</select>
Script
$('.nameofselect').on('change',function(){
alert( $(this).find('option:selected').val())
alert( $(this).find('option:selected').attr('value'))
});
Upvotes: 1
Reputation: 28513
You can use .val()
to get selected value
of select
tag :
var TheId = $('.nameofselect').val();
And if you want to read value attribute of option then use below :
$('.nameofselect option').each(function(){
alert($(this).val());
});
Upvotes: 0