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?
Try this
$("#foo option:selected").val();
edit: DEMO here
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());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With