Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 410
TKV Avatar asked May 03 '11 07:05

TKV


People also ask

How can I get multiple selected values of select box in jQuery?

With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.

What is the return type of get all selected options?

selectedOptions returns a list of selected items. Specifically, it returns a read-only HTMLCollection containing HTMLOptionElements. ... is spread syntax. It expands the HTMLCollection 's elements.


2 Answers

No jQuery:

// Return an array of the selected opion values
// 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>
like image 189
RobG Avatar answered Oct 08 '22 08:10

RobG


With jQuery, the usual way:

var values = $('#select-meal-type').val();

From the docs:

In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option;

like image 128
Felix Kling Avatar answered Oct 08 '22 09:10

Felix Kling