javascripthtmlhtml-select

How to get all selected values of a multiple select box?


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

Solution

  • No jQuery:

    // Return an array of the selected option values in the control.
    // 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>