How can I get a list of all values in select box?

前端 未结 4 2036
花落未央
花落未央 2021-02-05 02:10

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 un

相关标签:
4条回答
  • 2021-02-05 02:39

    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/

    0 讨论(0)
  • 2021-02-05 02:43

    Change:

    x.length
    

    to:

    x.options.length
    

    Link to fiddle

    And I agree with Abraham - you might want to use text instead of value

    Update
    The reason your fiddle didn't work was because you chose the option: "onLoad" instead of: "No wrap - in "

    0 讨论(0)
  • 2021-02-05 02:50

    As per the DOM structure you can use below code:

    var x = document.getElementById('mySelect');
         var txt = "";
         var val = "";
         for (var i = 0; i < x.length; i++) {
             txt +=x[i].text + ",";
             val +=x[i].value + ",";
          }
    
    0 讨论(0)
  • 2021-02-05 03:03

    It looks like placing the click event directly on the button is causing the problem. For some reason it can't find the function. Not sure why...

    If you attach the event handler in the javascript, it does work however.

    See it here: http://jsfiddle.net/WfBRr/7/

    <button id="display-text" type="button">Display text of all options</button>
    
    document.getElementById('display-text').onclick = function () {
        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);
    }
    
    0 讨论(0)
提交回复
热议问题