Total Pageviews

2018/06/11

[JavaScript] How to get selected value from a drop-down list that allows multiple selections ?

Problem
Assume I have a drop-down list that allows multiple selections.
1
2
3
4
5
6
7
   <select class="form-control" multiple id="importIntentList" 
           name="importIntentList" style="height: 100%;" size="20">
      <option value="1">A</option>
      <option value="2">B</option>
      <option value="3">C</option>
      <option value="4">D</option>
   </select>

I try to get selected value from the drop-down list, how to do it?


How-To
Here has code snippet to get values from the multi-selected drop-down list and push values into array:
1
2
3
4
5
6
7
   var intentSelectedOptions = [];
   var items = document.getElementById("importIntentList");
   for (var i = 0; i < items.options.length; i++) {
       if (items.options[i].selected == true) {
           intentSelectedOptions.push(items.options[i].value);
       }
   }


No comments: