How do I make the first option of selected with jQuery?
<select id="target">
<option value="1">...</option>
<option value="2">...</option>
</select>
How do I make the first option of selected with jQuery?
<select id="target">
<option value="1">...</option>
<option value="2">...</option>
</select>
When you use
$("#target").val($("#target option:first").val());
this will not work in Chrome and Safari if the first option value is null.
I prefer
$("#target option:first").attr('selected','selected');
because it can work in all browsers.
On the back of James Lee Baker's reply, I prefer this solution as it removes the reliance on browser support for :first :selected ...
$('#target').children().prop('selected', false);
$($('#target').children()[0]).prop('selected', 'selected');
For me, it only worked when I added the following line of code
$('#target').val($('#target').find("option:first").val());
You can select any option from dropdown by using it.
// 'N' can by any number of option. // e.g., N=1 for first option
$("#DropDownId").val($("#DropDownId option:eq(N-1)").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)
var firstItem = $("#interest-type").prop("selectedIndex", 0).val();
console.log(firstItem)