SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist anjanesh's Avatar
    Join Date
    Jun 2004
    Location
    Mumbai
    Posts
    447
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Adding OPTION to SELECT using appendChild

    Hi

    For some reason this doesnt work in IE.

    Code:
    var oSelect = document.createElement('select');
    oSelect.name = 'Year[]';
    for (var i=1950; i<=2005; i++)
     {
    		var oOption = document.createElement("option");
    		oOption.text = i;
    		oOption.value = i;
    		oSelect.appendChild(oOption);
     }
    oSelect.add(oOption); works in IE but doesnt in FF.
    Although, its mentioned here that appendChild applies to OPTION too.

    How do I get this working on both browsers ?

    Thanks
    Anjanesh

  2. #2
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Use the add() and remove() methods of the select instead.

    The add method takes 2 parameters, first one is the option node to add and the second one is the node to add before to. If you pass in null as the second argument, then the new option will be added in the last position.

    There is a diffrence how IE implemented this though (surprise!). And that is the second argument, instead IE expects a number where to add the option.

    A cross-browser solution could look like this:
    Code:
    <script type="text/javascript">
    var bIE = /MSIE/.test(navigator.userAgent);
    var oSelectNode = document.createElement("select");
    var oOptionNode = document.createElement("option");
    
    for(var i=1; i<=10; i++)
    {
    	var oOption = oOptionNode.cloneNode(false);
    	oOption.text = "Option nr. " + i;
    	oSelectNode.add(oOption, bIE? i : null);
    }
    
    document.body.appendChild(oSelectNode);
    </script>
    Though personally I think its really bad when you have to do browser detection, so an alternative would be to do it old school:
    Code:
    var oSelectNode = document.createElement("select");
    
    for(var i=0; i<10; i++)
    {
    	var oOption = new Option("Option nr. " + (i + 1));
    	oSelectNode.options[oSelectNode.options.length] = oOption;
    }
    
    document.body.appendChild(oSelectNode);

  3. #3
    SitePoint Addict jtrelfa's Avatar
    Join Date
    Oct 2004
    Location
    Troy, Mi
    Posts
    231
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The old school method has never failed me...DOM manipulation can sometimes be a pain.

    </two cents>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •