marky marky - 21 days ago 10
jQuery Question

Use jQuery to set selected index of a dropdown

I have seen other posts here at

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

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>
</select>


I need to reset the dropdown within an
$.ajax()
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

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.

$('#docsList').val('0');