Given a select, how to store in an array (using pure Javascript) the value of all the selected options?

1

The example for the select can be the same ..

 <form>
    <select id="mySelect" size="4" multiple> 
      <option>Apple</option>
      <option>Orange</option>
      <option>Pineapple</option>
      <option>Banana</option>
    </select>
</form>
    
asked by anonymous 22.03.2018 / 21:03

2 answers

1

You can use selectedOptions.

var mySelect = document.getElementById("mySelect");
mySelect.addEventListener("change", function (event) {
  var options = [].map.call(mySelect.selectedOptions, function (option) {
    return option.textContent;
  })
  console.log(options)
})
<select id="mySelect" size="4" multiple> 
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>
    
22.03.2018 / 21:12
0

If you just want the selected items in select in the array, using pure JavaScript, the code would look like this:

var sel = document.querySelector("#mySelect");

sel.addEventListener("change", function(){
   
   var opts = this.selectedOptions,
       frutas = [];

   for(var x=0; x<opts.length; x++){
      var txt = opts[x].textContent;
      if(!~frutas.indexOf(txt)) frutas.push(txt);
   }
   
   console.log(frutas);
});
<form>
    <select id="mySelect" size="4" multiple> 
      <option>Apple</option>
      <option>Orange</option>
      <option>Pineapple</option>
      <option>Banana</option>
    </select>
</form>
    
23.03.2018 / 07:32