How to get all selected values of a multiple selec

2019-01-01 06:55发布

问题:

I have a <select> element with the multiple attribute. How can I get this element\'s selected values using JavaScript?

Here\'s what I\'m trying:

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

回答1:

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

Quick example:

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


回答2:

Check-it Out:

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



回答3:

ES6

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

Where select is a reference to the <select> element.

To break it down:

  • [...select.options] takes the Array-like list of options and destructures it so that we can use Array.prototype methods on it (Edit: also consider using Array.from())
  • filter(...) reduces the options to only the ones that are selected
  • map(...) converts the raw <option> elements into their respective values


回答4:

Pretty much the same as already suggested but a bit different. About as much code as jQuery in Vanilla JS:

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

It seems to be faster than a loop in IE, FF and Safari. I find it interesting that it\'s slower in Chrome and Opera.

Another approach would be using selectors:

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


回答5:

suppose the multiSelect is the Multiple-Select-Element, just use its selectedOptions Property:

//show all selected options in the console:

for ( var i = 0; i < multiSelect.selectedOptions.length; i++) {
  console.log( multiSelect.selectedOptions[i].value);
}


回答6:

Here is an ES6 implementation:

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


回答7:

You Can try this script

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


回答8:

You can use [].reduce for a more compact implementation of RobG\'s approach:

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


回答9:

Same as the earlier answer but using underscore.js.

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


回答10:

My template helper looks like this:

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


回答11:

Check this:

HTML:

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

Javascript one line code

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


回答12:

Riot js code

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>


回答13:

You may use jquery plugin chosen .

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


回答14:

Building on Rick Viscomi\'s answer, try using the HTML Select Element\'s selectedOptions property:

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

In detail,

  • selectedOptions returns a list of selected items.
  • Specifically, it returns a read-only HTMLCollection containing HTMLOptionElements.
  • ... is spread syntax. It expands the HTMLCollection\'s elements.
  • [...] creates a mutable Array object from these elements, giving you an array of HTMLOptionElements.
  • map() replaces each HTMLObjectElement in the array (here called option) with its value (option.value).

Dense, but it seems to work.

Watch out, selectedOptions isn\'t supported by IE!