How do I make the first option of selected with jQuery?
<select id="target">
<option value="1">...</option>
<option value="2">...</option>
</select>
Changing the value of the select input or adjusting the selected attribute can overwrite the default selectedOptions property of the DOM element, resulting in an element that may not reset properly in a form that has had the reset event called.
Use jQuery's prop method to clear and set the option needed:
$("#target option:selected").prop("selected", false);
$("#target option:first").prop("selected", "selected");
One subtle point I think I've discovered about the top voted answers is that even though they correctly change the selected value, they do not update the element that the user sees (only when they click the widget will they see a check next to the updated element).
Chaining a .change() call to the end will also update the UI widget as well.
$("#target").val($("#target option:first").val()).change();
(Note that I noticed this while using jQuery Mobile and a box on Chrome desktop, so this may not be the case everywhere).
For me it only worked when I added the following code:
.change();
For me it only worked when I added the following code: As I wanted to "reset" the form, that is, select all the first options of all the selects of the form, I used the following code:
$('form').find('select').each(function(){
$(this).val($("select option:first").val());
$(this).change();
});
Check this best approach using jQuery with ECMAScript 6:
$('select').each((i, item) => {
var $item = $(item);
$item.val($item.find('option:first').val());
});
$('select#id').val($('#id option')[index].value)
Replace the id with particular select tag id and index with particular element you want to select.
i.e.
<select class="input-field" multiple="multiple" id="ddlState" name="ddlState">
<option value="AB">AB</option>
<option value="AK">AK</option>
<option value="AL">AL</option>
</select>
So here for first element selection I will use following code :
$('select#ddlState').val($('#ddlState option')[0].value)