Set active (Selected) item in listbox using javascript
Imported and modified from https://www.daftlogic.com/information-programmatically-preselect-dropdown-using-javascript.htm
HTML example:
<select id="ddl_example4" name="ddl_example4" >
<option value="AA" >item1</option >
<option value="BB" >item2</option >
<option value="CC" >item3</option >
<option value="DD" >item4</option >
<option value="EE" >item5</option >
<option value="FF" >item6</option >
</select >
<script >
// to change selection using name of option
setSelectedIndex_byname(document.getElementById('ddl_example4'),"item4");
function setSelectedIndex_byname(s, v) {
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].text == v) {
s.options[i].selected = true;
return;
}
}
}
// to change selection using value of option
setSelectedIndex_byval(document.getElementById("ddl_example4"),"BB");
function setSelectedIndex_byval(s, valsearch) {
// Loop through all the items in drop down list
for (i = 0; i < s.options.length; i++) {
if (s.options[i].value == valsearch) { // Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
return;
}
</script >
<select id="ddl_example4" name="ddl_example4" >
<option value="AA" >item1</option >
<option value="BB" >item2</option >
<option value="CC" >item3</option >
<option value="DD" >item4</option >
<option value="EE" >item5</option >
<option value="FF" >item6</option >
</select >
<script >
// to change selection using name of option
setSelectedIndex_byname(document.getElementById('ddl_example4'),"item4");
function setSelectedIndex_byname(s, v) {
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].text == v) {
s.options[i].selected = true;
return;
}
}
}
// to change selection using value of option
setSelectedIndex_byval(document.getElementById("ddl_example4"),"BB");
function setSelectedIndex_byval(s, valsearch) {
// Loop through all the items in drop down list
for (i = 0; i < s.options.length; i++) {
if (s.options[i].value == valsearch) { // Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
return;
}
</script >
Views 526
Downloads 137
CodeID
DB ID
ANmarAmdeen
602
Revisions
v1.0
Thursday
June
10
2021