marky marky - 1 year ago 62
jQuery Question

Use jQuery to set selected index of a dropdown

I have seen other posts here at

about this very same subject, but I have not found a solution that is setting the select using

I have a dropdown that looks like this:

<select type="select" id="docsList" name="docsList">
<option id="defaultListItem" value="0">Select a Document...</option>
<option value="38">Document 1</option>
<option value="35">Document 2</option>
<option value="46">Document 3</option>
<option value="45">Document 4</option>

I need to reset the dropdown within an
success function. I've used the following:

$('select#docsList option:selected').val('0');
$('select#docsList').attr('selectedIndex', 0);

... and some others.

I'm beginning to think this code is fine and I've got something else going on preventing resetting the dropdown.

Answer Source

You're overcomplicating things. You don't need jQuery to get/set a <select>'s selectedIndex.

$('#docsList').get(0).selectedIndex = 0;

When setting the value of a <select>, call .val() on the <select>, not on one of its <option>s.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download