如何在选择框中获取所有值的列表? [英] How can I get a list of all values in select box?

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

问题描述

我很困惑.我有一个带有下拉列表的表单,我想获取列表中所有值的列表.我从w3学校获得了以下示例(是的,我知道这是不可靠的,但是堆栈溢出的其他解决方案似乎与此非常相似).它对我不起作用,我尝试将其插入jsfiddle,但没有运气.

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:

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);
}

不适用于jsfiddle: http://jsfiddle.net/WfBRr/1/

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

但是,它在他们的网站上有效: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_option_text2

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

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

Any ideas on how to solve this?

推荐答案

您遇到了两个问题:

1)包含HTML的顺序.尝试在小提琴的JavaScript设置中将下拉列表从"onLoad"更改为"no wrap-head".

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)您的函数将打印这些值.您真正想要的是文本

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

x.options[i].text;代替x.options[i].value;

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

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

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