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

Asked

Viewed 110 times

1

The example for 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>

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>

0

If you really only want selected items on select in the array, using pure Javascript, the code would be 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.