javascript,在选择框中获取所有值的列表 [英] javascript, get list of all values in select box

查看:74
本文介绍了javascript,在选择框中获取所有值的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难过。我有一个带下拉列表的表单,我想获取列表中所有值的列表。我从w3学校拉下了下面的例子(是的,我知道这是不可靠的,但堆栈溢出的其他解决方案似乎与此非常相似)。这不是为我工作,我试图插入到jsfiddle,但没有运气。

  HTML:
< ; form>选择您最喜欢的水果:
< select id =mySelect>
< option value =a> Apple< / option>
< option value =o>橙色< /选项>
< option value =p>菠萝< / option>
< option value =b>香蕉< / option>
< / select>
< / form>
< button type =buttononclick =displayResult()>显示所有选项的文字< / button>

javascript:

  function displayResult(){
var x = document.getElementById(mySelect);
var txt =所有选项:;
var i;
for(i = 0; i< x.length; i ++){
txt = txt +\\\
+ x.options [i] .value;
}
alert(txt);
}

无法使用jsfiddle: http://jsfiddle.net/WfBRr/1/



然而,它可以在他们的网站上运行:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_option_text2

关于如何解决这个问题的任何想法?

解决方案

两个问题:

1)包含HTML的顺序。尝试在你的小提琴的JavaScript设置中将下拉列表从onLoad更改为no wrap-head。
$ b 2)你的函数打印这些值。你实际上要做的是文字

x.options [i] .text; 而不是 x.options [i] .value ;



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


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?

解决方案

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/

这篇关于javascript,在选择框中获取所有值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆