Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery and 'select' tag

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?

like image 894
daGrevis Avatar asked May 26 '26 04:05

daGrevis


2 Answers

Try this

$("#foo option:selected").val();

edit: DEMO here

like image 182
Null Pointer Avatar answered May 27 '26 17:05

Null Pointer


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());
});
like image 42
Phil Avatar answered May 27 '26 18:05

Phil