skip to Main Content

I ma trying to get selected values from select element with multiple attribute. jQuery would return an array, but javascript only retuerns single value if multiple are selected.

var fruits = document.getElementById('fruits')

fruits.addEventListener('change', function() {

  var selected = fruits.value
  console.log(selected)

})
<select multiple="true" id="fruits">
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
  <option value="mango">Mango</option>
  <option value="grape">Grape</option>
  <option value="watermelon">watermelon</option>
</select>

2

Answers


  1. using the selectedOptions you can access the currently selected elements

    var fruits = document.getElementById('fruits')
    
    fruits.addEventListener('change', function() {
    
      var selected = Array.from(fruits.selectedOptions, option => option.value);
      //or var selected = Array.from(fruits.selectedOptions).map(option => option.value);
      console.log(selected)
    
    })
    <select multiple="true" id="fruits">
      <option value="apple">Apple</option>
      <option value="banana">Banana</option>
      <option value="mango">Mango</option>
      <option value="grape">Grape</option>
      <option value="watermelon">watermelon</option>
    </select>
    Login or Signup to reply.
  2. The cleanest way would probably be to use the selectedOptions property

    const fruits = document.getElementById('fruits');
    const output = document.getElementById('selectedfruits');
    
    fruits.addEventListener('change', () => {
    
      var selected = Array.from(fruits.selectedOptions).map(el => el.value);
      
      output.innerText = JSON.stringify(selected);
    
    });
    <select multiple="true" id="fruits">
      <option value="apple">Apple</option>
      <option value="banana">Banana</option>
      <option value="mango">Mango</option>
      <option value="grape">Grape</option>
      <option value="watermelon">watermelon</option>
    </select>
    
    <output id="selectedfruits"></output>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search