【问题标题】:How to get all selected values of a multiple select box?如何获取多选框的所有选定值?
【发布时间】:2011-08-17 11:51:10
【问题描述】:

我有一个带有multiple 属性的<select> 元素。如何使用 JavaScript 获取此元素的选定值?

这是我正在尝试的:

function loopSelected() { 
    var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
    var selectedArray = new Array();
    var selObj = document.getElementById('slct'); 
    var i;
    var count = 0;
    for (i=0; i<selObj.options.length; i++) { 
        if (selObj.options[i].selected) {
            selectedArray[count] = selObj.options[i].value;
            count++; 
        } 
    } 
    txtSelectedValuesObj.value = selectedArray;
}

【问题讨论】:

  • 你写过代码吗?有了这将很容易帮助:)

标签: javascript html drop-down-menu


【解决方案1】:

签出:

HTML:

<a id="aSelect" href="#">Select</a>
<br />
<asp:ListBox ID="lstSelect" runat="server"  SelectionMode="Multiple" Width="100px">
    <asp:ListItem Text="Raj" Value="1"></asp:ListItem>
    <asp:ListItem Text="Karan" Value="2"></asp:ListItem>
    <asp:ListItem Text="Riya" Value="3"></asp:ListItem>
    <asp:ListItem Text="Aman" Value="4"></asp:ListItem>
    <asp:ListItem Text="Tom" Value="5"></asp:ListItem>
</asp:ListBox>

JQUERY:

$("#aSelect").click(function(){
    var selectedValues = [];    
    $("#lstSelect :selected").each(function(){
        selectedValues.push($(this).val()); 
    });
    alert(selectedValues);
    return false;
});

CLICK HERE TO SEE THE DEMO

【讨论】:

  • 不是粉丝——“HTML”不是 HTML(可读,但不是 HTML),答案需要添加 JQuery 作为依赖项。
【解决方案2】:

没有 jQuery:

// Return an array of the selected opion values
// select is an HTML select element
function getSelectValues(select) {
  var result = [];
  var options = select && select.options;
  var opt;

  for (var i=0, iLen=options.length; i<iLen; i++) {
    opt = options[i];

    if (opt.selected) {
      result.push(opt.value || opt.text);
    }
  }
  return result;
}

快速示例:

<select multiple>
  <option>opt 1 text
  <option value="opt 2 value">opt 2 text
</select>
<button onclick="
  var el = document.getElementsByTagName('select')[0];
  alert(getSelectValues(el));
">Show selected values</button>

【讨论】:

  • 感谢您的回答。你能帮我看看吗?我想我大部分都了解,但var options = select &amp;&amp; select.options; 是做什么的?根据我的经验,我预计会是var options = select.options;
  • select 不是 JavaScript 中最好的变量名。
  • @TecBrat var options = select &amp;&amp; select.options 在访问其属性之前确保 select 不是未定义的。
  • 我认为带有 && 的行没有多大意义......如果 select 未定义 getElementById 将返回 null。在这种情况下,一旦您尝试访问 length 属性,options 将是 null 和错误。但也许我错过了什么?
【解决方案3】:

与已经建议的几乎相同,但有点不同。 Vanilla JS 中的代码与 jQuery 差不多:

selected = Array.prototype.filter.apply(
  select.options, [
    function(o) {
      return o.selected;
    }
  ]
);

seems to be faster 比 IE、FF 和 Safari 中的循环。我觉得有趣的是它在 Chrome 和 Opera 中的速度较慢。

另一种方法是使用选择器:

selected = Array.prototype.map.apply(
    select.querySelectorAll('option[selected="selected"]'),
    [function (o) { return o.value; }]
);

【讨论】:

  • 第一个功能不是已经在Javascript中了吗?
  • 好的,知道了。但第一个可以更短。只需select.selectedOptions
  • 与使用库相比,这是裸 JS 的一个缺点。 reliable browser support 中缺少 selectedOptions 属性。像 jQuery 这样的库会对你隐藏它。自 2013 年以来发生了很多变化,但快速的谷歌显示人们仍然对 selectedOptions 有问题。
【解决方案4】:

与之前的答案相同,但使用 underscore.js。

function getSelectValues(select) {
    return _.map(_.filter(select.options, function(opt) { 
        return opt.selected; }), function(opt) { 
            return opt.value || opt.text; });
}

【讨论】:

    【解决方案5】:

    假设 multiSelect 是 Multiple-Select-Element,只需使用其 selectedOptions 属性:

    //show all selected options in the console:
    
    for ( var i = 0; i < multiSelect.selectedOptions.length; i++) {
      console.log( multiSelect.selectedOptions[i].value);
    }
    

    【讨论】:

    • 不只是发布代码,而是增加有关代码工作方式的详细信息。
    • 请不要把sn-p只给JS,没有HTML就没意义,只会报错
    • @ShadowWizard 知道了
    • 请注意,IE 不支持selectedOptionsdeveloper.mozilla.org/en-US/docs/Web/API/…
    【解决方案6】:

    你可以试试这个脚本

         <!DOCTYPE html>
        <html>
        <script>
        function getMultipleSelectedValue()
        {
          var x=document.getElementById("alpha");
          for (var i = 0; i < x.options.length; i++) {
             if(x.options[i].selected ==true){
                  alert(x.options[i].value);
              }
          }
        }
        </script>
        </head>
        <body>
        <select multiple="multiple" id="alpha">
          <option value="a">A</option>
          <option value="b">B</option>
          <option value="c">C</option>
          <option value="d">D</option>
        </select>
        <input type="button" value="Submit" onclick="getMultipleSelectedValue()"/>
        </body>
        </html>
    

    【讨论】:

      【解决方案7】:

      您可以使用[].reduce 更紧凑地实现RobG's approach

      var getSelectedValues =  function(selectElement) {
        return [].reduce.call(selectElement.options, function(result, option) {
          if (option.selected) result.push(option.value);
          return result;
        }, []);
      };
      

      【讨论】:

      • Array.prototype.filter 会是更好的选择[].filter.call(ele.options, e =&gt; e.selected)
      【解决方案8】:

      ES6

      [...select.options].filter(option => option.selected).map(option => option.value)
      

      其中select 是对&lt;select&gt; 元素的引用。

      分解:

      • [...select.options] 采用类似 Array 的选项列表并对其进行解构,以便我们可以在其上使用 Array.prototype 方法(编辑:也可以考虑使用 Array.from()
      • filter(...) 将选项减少到仅选择的选项
      • map(...) 将原始 &lt;option&gt; 元素转换为它们各自的值

      【讨论】:

      • 不错的功能实现:)
      • 你可以只使用 reduce() 方法My implementation
      • 如果你能得到 的 :checked children 的引用?
      • @Evgeny 有很多方法可以解决它。您应该在新答案中发布您的方法。
      • @Anentropic 这是一个很好的问题,但我认为效率并不重要,除非我们谈论成百上千个选项。
      【解决方案9】:

      我的模板助手看起来像这样:

       'submit #update': function(event) {
          event.preventDefault();
          var obj_opts = event.target.tags.selectedOptions; //returns HTMLCollection
          var array_opts = Object.values(obj_opts);  //convert to array
          var stray = array_opts.map((o)=> o.text ); //to filter your bits: text, value or selected
          //do stuff
      }
      

      【讨论】:

        【解决方案10】:

        防暴 js 代码

        this.GetOpt=()=>{
        
        let opt=this.refs.ni;
        
        this.logger.debug("Options length "+opt.options.length);
        
        for(let i=0;i<=opt.options.length;i++)
        {
          if(opt.options[i].selected==true)
            this.logger.debug(opt.options[i].value);
        }
        };
        
        //**ni** is a name of HTML select option element as follows
        //**HTML code**
        <select multiple ref="ni">
          <option value="">---Select---</option>
          <option value="Option1 ">Gaming</option>
          <option value="Option2">Photoshoot</option>
        </select>
        

        【讨论】:

          【解决方案11】:

          这是一个 ES6 实现:

          value = Array(...el.options).reduce((acc, option) => {
            if (option.selected === true) {
              acc.push(option.value);
            }
            return acc;
          }, []);
          

          【讨论】:

          • 这很好用。有趣的是,由于element.options 是实时集合,因此无法减少。如上述答案所示,它必须首先转换为数组。
          【解决方案12】:

          您可以使用选择的 jquery 插件。

          <head>
           <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css"
           <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
           <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script>
           <script>
                  jQuery(document).ready(function(){
                      jQuery(".chosen").data("placeholder","Select Frameworks...").chosen();
                  });
           </script>
          </head>
          
           <body> 
             <label for="Test" class="col-md-3 control label">Test</label>
                <select class="chosen" style="width:350px" multiple="true">
                      <option>Choose...</option>
                      <option>Java</option>                           
                      <option>C++</option>
                      <option>Python</option>
               </select>
           </body>
          

          【讨论】:

            【解决方案13】:

            基于Rick Viscomi 的回答,尝试使用HTML Select Element 的selectedOptions 属性:

            let txtSelectedValuesObj = document.getElementById('txtSelectedValues');
            [...txtSelectedValuesObj.selectedOptions].map(option => option.value);
            

            详细一点,

            • selectedOptions 返回所选项目的列表。
            • 具体来说,它返回一个包含HTMLOptionElements的只读HTMLCollection
            • ...spread syntax。它扩展了HTMLCollection 的元素。
            • [...] 从这些元素创建一个可变的 Array 对象,为您提供一个 HTMLOptionElements 数组。
            • map() 用其value (option.value) 替换数组中的每个HTMLObjectElement(此处称为option)。

            密集,但它似乎有效。

            当心,selectedOptions isn't supported IE!

            【讨论】:

              【解决方案14】:

              检查一下:

              HTML:

              <select id="test" multiple>
              <option value="red" selected>Red</option>
              <option value="rock" selected>Rock</option>
              <option value="sun">Sun</option>
              </select>
              

              Javascript 一行代码

              Array.from(document.getElementById("test").options).filter(option => option.selected).map(option => option.value);
              

              【讨论】:

                【解决方案15】:

                来吧。

                const arr = Array.from(el.features.selectedOptions) //get array from selectedOptions property
                const list = [] 
                arr.forEach(item => list.push(item.value)) //push each item to empty array
                console.log(list)
                

                【讨论】:

                  【解决方案16】:

                  您可以像这样创建自己的函数并在任何地方使用它

                  Pure JS

                  /**
                  * Get values from multiple select input field
                  * @param {string} selectId - the HTML select id of the select field
                  **/
                  function getMultiSelectValues(selectId) {
                   // get the options of select field which will be HTMLCollection
                   // remember HtmlCollection and not an array. You can always enhance the code by
                   // verifying if the provided select is valid or not
                    var options = document.getElementById(selectId).options; 
                      var values = [];
                      
                     // since options are HtmlCollection, we convert it into array to use map function on it
                      Array.from(options).map(function(option) {
                          option.selected ? values.push(option.value) : null
                      })
                  
                      return values;
                  }
                  

                  你可以在一行中使用 jQuery 获得相同的结果

                  $('#select_field_id').val()
                  

                  这将返回well的值数组。

                  【讨论】:

                    【解决方案17】:

                    来自HTMLSelectElement.selectedOptions - Web APIs | MDN的示例

                    let orderButton = document.getElementById("order");
                    let itemList = document.getElementById("foods");
                    let outputBox = document.getElementById("output");
                    
                    orderButton.addEventListener("click", function() {
                      let collection = itemList.selectedOptions;
                      let output = "";
                    
                      for (let i = 0; i < collection.length; i++) {
                        if (output === "") {
                          output = "Your order for the following items has been placed: ";
                        }
                        output += collection[i].label;
                    
                        if (i === (collection.length - 2) && (collection.length < 3)) {
                          output += " and ";
                        } else if (i < (collection.length - 2)) {
                          output += ", ";
                        } else if (i === (collection.length - 2)) {
                          output += ", and ";
                        }
                      }
                    
                      if (output === "") {
                        output = "You didn't order anything!";
                      }
                    
                      outputBox.innerHTML = output;
                    }, false);
                    <label for="foods">What do you want to eat?</label><br>
                    <select id="foods" name="foods" size="7" multiple>
                      <option value="1">Burrito</option>
                      <option value="2">Cheeseburger</option>
                      <option value="3">Double Bacon Burger Supreme</option>
                      <option value="4">Pepperoni Pizza</option>
                      <option value="5">Taco</option>
                    </select>
                    <br>
                    <button name="order" id="order">
                      Order Now
                    </button>
                    <p id="output">
                    </p>

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 2015-02-19
                      • 2013-07-15
                      • 1970-01-01
                      • 1970-01-01
                      • 2015-01-10
                      • 1970-01-01
                      相关资源
                      最近更新 更多