how to access multiple select array data in javascript

Priyanshu picture Priyanshu · May 8, 2013 · Viewed 14.7k times · Source

I have a multiple select box and I want to access the selected data in javascript. Here is the code:

<form onsubmit="return false;" id="multisel">
  <select name="a[]" id="a" multiple style="width:350px;" tabindex="4">
    <option value="Pedro">1</option>
    <option value="Alexis">2</option>
    <option value="Messi">3</option>
    <option value="Villa">4</option>
    <option value="Andres">5</option>
    <option value="Sergio">6</option>
    <option value="Xavi">7</option>
  </select>

  <button id="btn1" onclick="ajaxmultiselect()" type="submit" class="btn btn-primary">Save changes</button>

  <p id="status"></p>
</form>

Here is the code I have tried so far :

<script>    
function ajaxmultiselect(){
  var input  = [];
  input = document.getElementById("a").value;
  var status = _("status");
  if(input == ""){
    status.innerHTML = "Fill out all of the form data";
  }else {
    status.innerHTML = input;
  }
}
</script>

When I run the code it only gives the first value. I tried to access the values in php and it works fine, it passes the value as an array in php. Why isn't it doing the same with javascript?

I also tried to run a loop for the length of the value but that calculates the length of the first selection only. I want to display all the values that will be selected.

Any help will be appreciated.

Answer

Goodwine picture Goodwine · May 8, 2013

You can do the following:

function getSelectedOptions(element) {
    // validate element
    if(!element || !element.options)
        return []; //or null?

    // return HTML5 implementation of selectedOptions instead.
    if (element.selectedOptions)
        return element.selectedOptions;

    // you are here because your browser doesn't have the HTML5 selectedOptions
    var opts = element.options;
    var selectedOptions = [];
    for(var i = 0; i < opts.length; i++) {
         if(opts[i].selected) {
             selectedOptions.push(opts[i]);
         }
    }
    return selectedOptions;
}

and then change your ajaxmultiselect() so you call it like this:

input = getSelectedOptions(document.getElementById("a"));

You will have to iterate for the values tho.