how to change the selected value in javascript and get the selected value in codebehind page? AutoPostBack is set to false.
Asked
Active
Viewed 8.9k times
2 Answers
28
You can change it like this:
var ddl = document.getElementById('ddl-id');
var opts = ddl.options.length;
for (var i=0; i<opts; i++){
if (ddl.options[i].value == "some-value"){
ddl.options[i].selected = true;
break;
}
}

Software Engineer
- 3,906
- 1
- 26
- 35
-
but when your page gets postback the value will be changed to which was set by the pageload. then what to do??? – King of kings Sep 16 '14 at 10:21
15
//setting the value of a drop down list
document.getElementById('my_drop_down').selectedIndex=2;

Avi Y
- 2,456
- 4
- 29
- 35
-
1I am not sure what you mean by 'code behind page'. But this is the way to get the selected value of a dropdown list: document.getElementById('dropdown').value – Avi Y Apr 08 '12 at 07:44
-
To add to Avi Y's comment, selectedIndex of 2 is the 3rd item in the list, since the index starts at 0. Also, setting the index to -1, clears the dropdown of any text. https://www.w3schools.com/jsref/prop_select_selectedindex.asp#:~:text=Definition%20and%20Usage,of%20the%20first%20option%20selected. – ctay Jun 30 '20 at 14:24