views:

36

answers:

1

Hello I am trying to get the options from a html select element. The logic I am using is working in firefox, but it isn't working in IE. It gives me the length of the options array or the number of options but it isn't giving me the values of options. How do I troubleshoot this issue??

var SelectId= 'select_1'; //id of the html select element
options = document.getElementById(SelectId).options;
alert(options.length);
for(var o=0;o< options.length;o++)
{alert(options[o].value);}
A: 

The following code should put the values into a "vals" array.

var sel = document.getElementById('select_1');
var vals = [];
for (var i = 0; i < sel.children.length; ++i) {
    var child = sel.children[i];
    if (child.tagName == 'OPTION') vals.push(child.value);
}
// vals now contains the values
sunetos
hye sunetos! It is giving me a blank value in IE. It is giving me the correct value in FF though!
sai
Can you paste what is showing up as blank? I just verified my code in IE8. Just to make sure it's clear what it's doing, the vals array now contains the string "value" property of each "OPTION" child tag.
sunetos
var sel = document.getElementById(rA[i].id);var vals = []; for (var o = 0; o < sel.children.length; ++o) { var child = sel.children[o]; if (child.tagName == 'OPTION') vals.push(child.value); } for(var s in vals) {alert(vals[s]);}I did not make a change to the code you posted! But it still gives me a blank message!It works in FF though! I am using IE8 too!
sai
Your exact code works on my test page. Can you provide the HTML of the page you're using (or better, a link to the page)?
sunetos
dude it worked! the problem is it isn't child.value, child.text worked!! thanks var sel = document.getElementById(rA[i].id); var vals = []; for (var o = 0; o < sel.children.length; ++o) { var child = sel.children[o]; if (child.tagName == 'OPTION') vals.push(child.text); } for(var s in vals) {alert(vals[s]);}
sai
thanks for the help!
sai
No problem! Be careful though, there is a difference between the text and the value. If this is in a form which you intend to post to a server, the "value" property is what will get used, not the text. Example: <select id="select_1" name="select_1"> <option value="foo">bar</option> </select>If that is in a form that gets posted, the server will get "select_1=foo" and not "select_1=bar".
sunetos
Ok Sir! point noted! thanks!
sai