We come across a lot of instances where we need to set the values of form elements programmatically using client side script. To set the value of a select list (in case of multiple select or single select), the best way to do it is to loop through the options, checking if the value matches and then setting [option].selected = true.
For example:
//here for simplicity i am considering a single select case
function setSelectValue(selectList, val) {
for (option in selectList.options) {
if (option.value == val) {
option.selected = true;
break;
}
}
}
This piece of code will work for almost all web browsers. But not so surprisingly there is a difference in the way IE and other browsers handle the select list. In Firefox a listitem given without a specific value attribute considers the given text as the value. Though IE also gives the same result on post back, while programmatically checking the value of an option it says its undefined. So you cannot use the setSelectValue function for <li>Hello</li> in IE. To make it work for IE you have to explicitly give <li value=”Hello”>Hello</li>.
Not a big deal but it cost me half a day 😉