Javascript Get Values from Multiple Select Option Box

前端 未结 4 683
我寻月下人不归
我寻月下人不归 2020-11-29 08:38

This one is driving me nuts. It’s got to be something simple and stupid that I am overlooking. I have a multiple select box in a form. I am just trying to get the values th

相关标签:
4条回答
  • 2020-11-29 08:46

    Also, change this:

        SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;
    

    to

        SelBranchVal = SelBranchVal + InvForm.SelBranch[x].value+ "," ;
    

    The reason is that for the first time the variable SelBranchVal will be empty

    0 讨论(0)
  • 2020-11-29 08:48

    Here i am posting the answer just for reference which may become useful.

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    function show()
    {
         var InvForm = document.forms.form;
         var SelBranchVal = "";
         var x = 0;
         for (x=0;x<InvForm.kb.length;x++)
             {
                if(InvForm.kb[x].selected)
                {
                 //alert(InvForm.kb[x].value);
                 SelBranchVal = InvForm.kb[x].value + "," + SelBranchVal ;
                }
             }
             alert(SelBranchVal);
    }
    </script>
    </head>
    <body>
    <form name="form">
    <select name="kb" id="kb" onclick="show();" multiple>
    <option value="India">India</option>
    <option selected="selected" value="US">US</option>
    <option value="UK">UK</option>
    <option value="Japan">Japan</option>
    </select>
    <!--input type="submit" name="cmdShow" value="Customize Fields"
     onclick="show();" id="cmdShow" /-->
    </form>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-29 08:50

    Take a look at HTMLSelectElement.selectedOptions.

    HTML

    <select name="north-america" multiple>
      <option valud="ca" selected>Canada</a>
      <option value="mx" selected>Mexico</a>
      <option value="us">USA</a>
    </select>
    

    JavaScript

    var elem = document.querySelector("select");
    
    console.log(elem.selectedOptions);
    //=> HTMLCollection [<option value="ca">Canada</option>, <option value="mx">Mexico</option>]
    

    This would also work on non-multiple <select> elements


    Warning: Support for this selectedOptions seems pretty unknown at this point

    0 讨论(0)
  • The for loop is getting one extra run. Change

    for (x=0;x<=InvForm.SelBranch.length;x++)
    

    to

    for (x=0; x < InvForm.SelBranch.length; x++)
    
    0 讨论(0)
提交回复
热议问题