Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 677
marky Avatar asked Nov 28 '22 18:11

marky


2 Answers

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');
like image 85
Matt Ball Avatar answered Dec 05 '22 17:12

Matt Ball


$('#docsList option[value=0]').attr('selected', 'selected');
This will set the <option> with the value attribute set to 0 as the selected option.

like image 21
Justin Schwartzenberger Avatar answered Dec 05 '22 18:12

Justin Schwartzenberger