SitePoint Sponsor |
|
User Tag List
Results 1 to 3 of 3
-
Aug 23, 2006, 04:06 #1
- 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); }
Although, its mentioned here that appendChild applies to OPTION too.
How do I get this working on both browsers ?
ThanksAnjanesh
-
Aug 23, 2006, 11:45 #2
- 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>
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);
-
Aug 24, 2006, 04:31 #3
- 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