Browser Bug: Select dropdown element's add() method doesn't work as expected (IE)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    Browser Bug: Select dropdown element's add() method doesn't work as expected (IE)

    Problem
    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:
    [CODE=javascript]var opt = document.create Element("option ");
    opt.name = "optName";
    opt.value = "optValue";
    var selObj = document.getEle mentById("selte st");
    selObj.add(opt, null);[/CODE]
    Solution
    IE does not support the W3C add method, so we have to use a try/catch to use its proprietary method instead:[CODE=javascript]var opt = document.create Element("option ");
    opt.name = "optName";
    opt.value = "optValue";
    var selObj = document.getEle mentById("selte st");
    try {
    selObj.add(opt, null);
    } catch (e) {
    selObj.add(opt) ; // for IE only
    }[/CODE]

    -----------------------------------------------------------------------------------------------------
    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:
    [CODE=javascript]var opt = document.create Element("option ");
    opt.name = "optName";
    opt.value = "optValue";
    var selObj = document.getEle mentById("selte st");
    // let's say we want to add before the currently selected option
    var optToAddBefore = selObj.options[selObj.selected Index];
    selObj.add(opt, optToAddBefore) ;[/CODE]
    Solution
    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:[CODE=javascript]var opt = document.create Element("option ");
    opt.name = "optName";
    opt.value = "optValue";
    var selObj = document.getEle mentById("selte st");
    // let's say we want to add before the currently selected option
    var optToAddBefore = selObj.options[selObj.selected Index];
    try {
    selObj.add(opt, optToAddBefore) ;
    } catch (e) {
    selObj.add(opt, selObj.selected Index); // for IE only
    }[/CODE]

    More Bugs, Quirks and Inconsistencies
Working...