Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
71
rated 0 times [  75] [ 4]  / answers: 1 / hits: 152778  / 11 Years ago, wed, august 7, 2013, 12:00:00

I am stumped. I have a form with a dropdown list, and I would like to grab a list of all the values in the list. I pulled the below example from w3 schools (yes, I know it's unreliable, but other solutions on stack overflow seem to be very similar to this). It was not working for me, and I tried plugging it into jsfiddle, but no luck.



HTML:
<form>Select your favorite fruit:
<select id=mySelect>
<option value=a>Apple</option>
<option value=o>Orange</option>
<option value=p>Pineapple</option>
<option value=b>Banana</option>
</select>
</form>
<button type=button onclick=displayResult()>Display text of all options</button>


javascript:



function displayResult() {
var x = document.getElementById(mySelect);
var txt = All options: ;
var i;
for (i = 0; i < x.length; i++) {
txt = txt + n + x.options[i].value;
}
alert(txt);
}


Not working on jsfiddle: http://jsfiddle.net/WfBRr/1/



However, it works at their site:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_option_text2



Any ideas on how to solve this?


More From » html

 Answers
14

You had two problems:



1) The order in which you included the HTML. Try changing the dropdown from onLoad to no wrap - head in the JavaScript settings of your fiddle.



2) Your function prints the values. What you're actually after is the text



x.options[i].text; instead of x.options[i].value;



http://jsfiddle.net/WfBRr/5/


[#76471] Tuesday, August 6, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neilshamarh

Total Points: 181
Total Questions: 94
Total Answers: 104

Location: Guadeloupe
Member since Sat, Aug 22, 2020
4 Years ago
;