The select object's add method doesn't append options to the end of the list.
Browser
Internet Explorer
Example
The Javascript code for appending an option element at the end of a select dropdown list:
Expand|Select|Wrap|Line Numbers
- var opt = document.createElement("option");
- opt.name = "optName";
- opt.value = "optValue";
- var selObj = document.getElementById("seltest");
- selObj.add(opt,null);
IE does not support the W3C add method, so we have to use a try/catch to use its proprietary method instead:
Expand|Select|Wrap|Line Numbers
- var opt = document.createElement("option");
- opt.name = "optName";
- opt.value = "optValue";
- var selObj = document.getElementById("seltest");
- try {
- selObj.add(opt,null);
- } catch (e) {
- selObj.add(opt); // for IE only
- }
Problem
The select object's add method doesn't add options to the list. This is similar to the previous problem (appending to the end of the list), but with a slightly different solution.
Browser
Internet Explorer
Example
The Javascript code for adding an option element to a select dropdown list:
Expand|Select|Wrap|Line Numbers
- var opt = document.createElement("option");
- opt.name = "optName";
- opt.value = "optValue";
- var selObj = document.getElementById("seltest");
- // let's say we want to add before the currently selected option
- var optToAddBefore = selObj.options[selObj.selectedIndex];
- selObj.add(opt,optToAddBefore);
IE does not support the W3C add method, so we have to use a try/catch to use its proprietary method instead. For the second argument, instead of the option element, we have to pass the selected index:
Expand|Select|Wrap|Line Numbers
- var opt = document.createElement("option");
- opt.name = "optName";
- opt.value = "optValue";
- var selObj = document.getElementById("seltest");
- // let's say we want to add before the currently selected option
- var optToAddBefore = selObj.options[selObj.selectedIndex];
- try {
- selObj.add(opt,optToAddBefore);
- } catch (e) {
- selObj.add(opt,selObj.selectedIndex); // for IE only
- }