Reputation: 21333
I have a <select>
tag and I need to select the value of the selected option.
<select id="foo">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
With jQuery I try to use the val()
method to do it like this:
$('#foo').val();
The problem is that it always returns 1
- the default value of the selected option!
Why is that so?
Upvotes: 2
Views: 24397
Reputation: 551
This could also happen if you have more than one DOM element with the id attribute you are using in your selector.
jQuery will bind events correctly to all of the elements, but then use only the first one in DOM when requesting its value.
Upvotes: 0
Reputation: 227
$("select option:selected").each(function () {
$(this).val();
});
Upvotes: 0
Reputation: 87073
Try this:
$('#foo :selected').val();
Check this:
$('#foo').change(function() {
console.log($('#foo :selected').val());
}).change(); // this change will fire for first time and give the value `1`
Upvotes: 2
Reputation: 164895
When a <select>
element contains no options with the selected
attribute, it defaults to selecting the first option.
If you change the selection and run val()
, you will get a different value.
Try this and tell me if it still gives you the same value every time it changes
$('#foo').change(function() {
console.log($(this).val());
});
Upvotes: 2