Javascript 如何获取多选框的所有选定值?

Javascript 如何获取多选框的所有选定值?,javascript,html,drop-down-menu,Javascript,Html,Drop Down Menu,我有一个元素,具有multiple属性。如何使用JavaScript获取此元素的选定值 以下是我正在尝试的: function loopSelected() { var txtSelectedValuesObj = document.getElementById('txtSelectedValues'); var selectedArray = new Array(); var selObj = document.getElementById('slct');

我有一个
元素,具有
multiple
属性。如何使用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;
}
函数loopSelected(){
var txtSelectedValuesObj=document.getElementById('txtSelectedValues');
var selectedArray=新数组();
var selObj=document.getElementById('slct');
var i;
var计数=0;

对于(i=0;i请查看:

<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>
$("#aSelect").click(function(){
    var selectedValues = [];    
    $("#lstSelect :selected").each(function(){
        selectedValues.push($(this).val()); 
    });
    alert(selectedValues);
    return false;
});
<select id="test" multiple>
<option value="red" selected>Red</option>
<option value="rock" selected>Rock</option>
<option value="sun">Sun</option>
</select>
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>
$("#aSelect").click(function(){
    var selectedValues = [];    
    $("#lstSelect :selected").each(function(){
        selectedValues.push($(this).val()); 
    });
    alert(selectedValues);
    return false;
});
<select id="test" multiple>
<option value="red" selected>Red</option>
<option value="rock" selected>Rock</option>
<option value="sun">Sun</option>
</select>

查看:

<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>
$("#aSelect").click(function(){
    var selectedValues = [];    
    $("#lstSelect :selected").each(function(){
        selectedValues.push($(this).val()); 
    });
    alert(selectedValues);
    return false;
});
<select id="test" multiple>
<option value="red" selected>Red</option>
<option value="rock" selected>Rock</option>
<option value="sun">Sun</option>
</select>
/**
* 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;
}
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>
$("#aSelect").click(function(){
    var selectedValues = [];    
    $("#lstSelect :selected").each(function(){
        selectedValues.push($(this).val()); 
    });
    alert(selectedValues);
    return false;
});
<select id="test" multiple>
<option value="red" selected>Red</option>
<option value="rock" selected>Rock</option>
<option value="sun">Sun</option>
</select>

无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;
}
/**
* 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;
}
//返回所选opion值的数组
//select是一个HTML选择元素
函数getSelectValues(选择){
var结果=[];
var options=select&&select.options;
var-opt;
对于(var i=0,iLen=options.length;iNo 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;
}
//返回所选opion值的数组
//select是一个HTML选择元素
函数getSelectValues(选择){
var结果=[];
var options=select&&select.options;
var-opt;

对于(var i=0,iLen=options.length;i与前面建议的基本相同,但有点不同。大约与jQuery中的代码一样多:

这比IE、FF和Safari中的循环要慢。我觉得有趣的是,Chrome和Opera中的循环要慢

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

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

与前面建议的基本相同,但有点不同。大约与jQuery中的代码相同:

这比IE、FF和Safari中的循环要慢。我觉得有趣的是,Chrome和Opera中的循环要慢

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

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

与前面的答案相同,但使用下划线.js

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

与前面的答案相同,但使用下划线.js

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

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

//show all selected options in the console:

for ( var i = 0; i < multiSelect.selectedOptions.length; i++) {
  console.log( multiSelect.selectedOptions[i].value);
}
//在控制台中显示所有选定的选项:
对于(变量i=0;i
假设multiSelect是Multiple Select元素,只需使用其selectedOptions属性:

//show all selected options in the console:

for ( var i = 0; i < multiSelect.selectedOptions.length; i++) {
  console.log( multiSelect.selectedOptions[i].value);
}
//在控制台中显示所有选定的选项:
对于(变量i=0;i
您可以尝试此脚本

     <!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>

函数getMultipleSelectedValue()
{
var x=document.getElementById(“alpha”);
对于(变量i=0;i
您可以尝试此脚本

     <!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>

函数getMultipleSelectedValue()
{
var x=document.getElementById(“alpha”);
对于(变量i=0;i
您可以使用
[]。减少
以更紧凑地实现:


您可以使用
[].reduce
更紧凑地实现:

ES6

[...select.options].filter(option => option.selected).map(option => option.value)
其中,
select
是对
元素的引用

要分解它:

    > [选择…选项] 采用数组类似的选项列表并对其进行结构分解,以便我们可以在其中使用ARARY.TRAIL方法(编辑:也可以考虑使用<代码>数组>())< /LI>
  • filter(…)
    将选项减少为仅选定的选项
  • map(…)
    将原始
    元素转换为各自的值
    • ES6

      [...select.options].filter(option => option.selected).map(option => option.value)
      
      其中,
      select
      是对
      元素的引用

      要分解它:

        > [选择…选项] 采用数组类似的选项列表并对其进行结构分解,以便我们可以在其中使用ARARY.TRAIL方法(编辑:也可以考虑使用<代码>数组>())< /LI>
      • filter(…)
        将选项减少为仅选定的选项
      • map(…)
        将原始
        元素转换为各自的值

      我的模板助手如下所示:

       '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
      }
      

      我的模板助手如下所示:

       '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
      }
      

      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>
      
      this.GetOpt=()=>{
      设opt=this.refs.ni;
      this.logger.debug(“选项长度”+option.Options.length);
      
      对于(设i=0;ijs代码

      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>
      
      this.GetOpt=()=>{
      设opt=this.refs.ni;
      this.logger.debug(“选项长度”+option.Options.length);
      
      对于(设i=0;i这里是一个ES6实现:

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

      下面是一个ES6实现:

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

      您可以使用所选的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>
      
      
      
      您可以使用所选的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>
      
      
      基于的答案,尝试使用HTML Select元素的属性:

      让txtSelectedValuesObj=document.getElementById('txtSelectedValues');
      […txtSelectedValuesObj.selectedOptions].map(option=>option.value);
      
      具体地说,

      • selectedOptions
        返回所选项目的列表
      • 具体来说,它返回一个只读的包含
      • 是。它扩展
        HTMLCollection
        的元素
      • […]
        从这些元素创建一个可变的
        数组
        对象,为您提供一个
        HTMLOptionElements的数组
      • map()
        用其(
        option.value
        )替换数组中的每个
        HTMLObjectElement
      密度很高,但似乎有效

      请注意,
      selectedOptions
      by IE!

      基于的答案,尝试使用HTML Select元素的属性:

      让txtSelectedValuesObj=document.getElementById('txtSelectedValues');
      […txt