Changing it with jQuery select doesn't show selected option

Jovica picture Jovica · Dec 3, 2010 · Viewed 32.2k times · Source

I have hidden form with a few select fields and some input fields. Click on button should show that form and set some values in the fields. The input fields are filled with given values but I have problem with select fields.

Using this code:

$("#form select[name=user]").val(value);

option with that value gets attribute "selected" (checked in Firebug) but select field still shows "Choose" (initial) option.

I tried to do focus and blur after setting value but that didn't work either.

Any suggestions?


This is pretty much the standard form:

<form action="#" id="form" class="fix">
<div class="holder">
    <label>User:</label>
    <select name="user" class="styled">
        <option value="0" selected>Choose</option>
        <option value="1">User 1</option>
        <option value="2">User 2</option>
        </select>
    </div>
</form>

And by calling jQuery statement:

$("#form select[name=user]").val('2');
$("#form").show();

I get this in Firebug:

<form action="#" id="form" class="fix" style="display:none">
<div class="holder">
    <label>User:</label>
    <select name="user" class="styled">
        <option value="0">Choose</option>
        <option value="1">User 1</option>
        <option value="2" selected>User 2</option>
        </select>
    </div>
</form>

but the text is select stays "Choose". If I submit form, the value is correctly passed.

Than if I reset the form and select some option the text of selected option is shown properly. That's what's weird to me.

Answer

Jovica picture Jovica · Dec 10, 2010

I found a solution. I forgot to call change event for . I didn't know that jQuery doesn't do it automatically. So the code for solution is:

$("form select[name=user]").val(value).change();