How do I set the index of a dropdown in jQuery if the way I'm finding the control is as follows:
$("*[id$='" + originalId + "']")
I do it this way because I'm creating controls dynamically and since the ids are changed when using Web Forms, I found this as a work around to find me some controls. But once I have the jQuery object, I do not know how to set the selected index to 0 (zero).
This question is related to
jquery
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();
This will work:
<head>
<script type="text/javascript">
function Init () {
var counter = document.getElementById ("counter");
for (var i = 1; i < 1000; i++) {
var option = new Option (i, i);
counter.options.add (option);
}
counter.focus ();
}
function OnKeyPressCounter (event, counter) {
var chCode = ('charCode' in event) ? event.charCode : event.keyCode;
if (chCode == 68 /* + */) {
if (counter.selectedIndex < counter.options.length - 1) {
counter.selectedIndex++;
}
}
if (chCode == 45 /* - */) {
if (counter.selectedIndex > 0) {
counter.selectedIndex--;
}
}
}
</script>
</head>
<body onload="Init ()">
Use the + and - keys to increase/decrease the counter.
<select id="counter" onkeypress="OnKeyPressCounter(event, this)" style="width:80px"></select>
</body>
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');
$("[id$='" + originalId + "']").val("0 index value");
will set it to 0
I'm using
$('#elem').val('xyz');
to select the option element that has value='xyz'
This also work proper in chrome and internet Explorer
$("#MainContent_cmbEvalStatus").prop("selectedIndex", 1).change();
Put according your choice possition value of DropDown 0,1,2,3,4.....
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>
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);
You want to grab the value of the first option in the select element.
$("*[id$='" + originalId + "']").val($("*[id$='" + originalId + "'] option:first").attr('value'));
Source: Stackoverflow.com