Using the jQuery change() method; you can set the selected value of dropdown in jquery by using id, name, class, and tag with selected html elements; see the following example for that: Example 1 :- Set selected value of dropdown in jquery by id.
First of all - that selector is pretty slow. It will scan every DOM element looking for the ids. It will be less of a performance hit if you can assign a class to the element.
$(".myselect")
To answer your question though, there are a few ways to change the select elements value in jQuery
// sets selected index of a select box to the option with the value "0"
$("select#elem").val('0');
// sets selected index of a select box to the option with the value ""
$("select#elem").val('');
// sets selected index to first item using the DOM
$("select#elem")[0].selectedIndex = 0;
// sets selected index to first item using jQuery (can work on multiple elements)
$("select#elem").prop('selectedIndex', 0);
Just found this, it works for me and I personally find it easier to read.
This will set the actual index just like gnarf's answer number 3 option.
// sets selected index of a select box the actual index of 0
$("select#elem").attr('selectedIndex', 0);
This didn't used to work but does now... see bug: http://dev.jquery.com/ticket/1474
As recommended in the comments use :
$("select#elem").prop('selectedIndex', 0);
I'm writing this answer in 2015, and for some reason (probably older versions of jQuery) none of the other answers have worked for me. I mean, they change the selected index, but it doesn't actually reflect on the actual dropdown.
Here is another way to change the index, and actually have it reflect in the dropdown:
$('#mydropdown').val('first').change();
JQuery code:
$("#sel_status").prop('selectedIndex',1);
Jsp Code:
Status:
<select name="sel_status"
id="sel_status">
<option value="1">-Status-</option>
<option>ALL</option>
<option>SENT</option>
<option>RECEIVED</option>
<option>DEACTIVE</option>
</select>
I'm using
$('#elem').val('xyz');
to select the option element that has value='xyz'
You want to grab the value of the first option in the select element.
$("*[id$='" + originalId + "']").val($("*[id$='" + originalId + "'] option:first").attr('value'));
To select the 2nd option
$('#your-select-box-id :nth-child(2)').prop('selected', true);
Here we add the `trigger('change') to make the event fire.
$('#your-select-box-id :nth-child(2)').prop('selected', true).trigger('change');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With