1

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.

1
  • A better way of accessing that value is document.forms[0].a.value. document.forms[0] is the first form and form.a is the element with ID 'a' in that form. Commented May 8, 2013 at 19:34

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

If you are wanting to get multiple selected items you could try something like the following:

function GetSelectedItems() {
            var select = document.forms[0].a;
            var selectedList = [];

            for (var i = 0; i < select.options.length; i++) {
                if (select.options[i].selected) {
                    selectedList.push(select.options[i].value);
                }
            }

            alert(Array.join(selectedList, ","));
        }

5 Comments

Hi, Thanks for the reply, I did manage to display a csv of the selected options (with your code help ). Now how can I check if it is behaving as an array after joining ?? Is there any way to display it, I want to do that because I am passing the end result in an AJAX request to php, but the response is blank.
So instead of Array.join you could just return the array object. The Array.join converts it to a string. In my example just return selectedList in place of the alert.
When I display the selectedList as it is from your example, without using AJAX, it displays a csv. But when I send the same selectedList through ajax the response text is blank. Also, php recognises the selectedList as an array, since I dont get any errors from the foreach loop that I am using in the code. When I send the alert, php doesnt take it as an array.
I am sorry.. My bad... php doesnt recognize selectedList as an array. I have to explode it to make an array which is still blank.
If you are wanting to pass this off to the server side on a post back, you will just read it in from the name on your control. I am not 100% sure, but I don't know if you can have [] in your control name. I believe through UrlEncoding the [] will be replaced and possibly change the name of the control data in the querystring or form collection. I do not write PHP, so I am not in the know there. If you are just validating then you can check to see the length of the array and perform a task based on the length.
0

For a given <select> element, all of the selected options are in the selectedOptions property. The selectedIndex property has the index of the first selected option, or -1 if there is no selection. Each of the options are the DOM object for that element, so their value is in the value property. So:

function ajaxmultiselect(){
  var input  = [];
  var select = document.forms[0].a;
  var status = _("status");
  var options = select.selectedOptions;
  if(select.selectedIndex == -1){
    // no selection
    status.innerHTML = "Fill out all of the form data";
  }else {
    for (var i = 0; i < options.length)
      input.push(options[i].value);
    status.innerHTML = input.join(", ");
  }
}

From there you should be able to derive whatever you want.

4 Comments

I believe selectedOptions is a thingy only from WebKit (Chrome and Opera), so FF doesn't work with this, and maybe IE doesn't work either. Look at this page, it shows Mozilla hasn't implemented it yet: developer.mozilla.org/en-US/docs/DOM/HTMLSelectElement;
I actually noticed because I'm using FF atm, if I was using Chrome, I would have answered the same as you xD
My life (as a hobby web designer) would be so much simpler if every rendering engine was interchangeable (with WebKit). WebKit is awesome. FYI, Safari is also WebKit.
forget about webkit, Blink is the new tomorrow
0
document.getElementById('a').options //All Options

This will give you an array of options that you can iterate through.

1 Comment

This doesn't work on Firefox tho, maybe it doesn't work in IE either, look at this page to see that Mozilla hasn't implemented it yet: developer.mozilla.org/en-US/docs/DOM/HTMLSelectElement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.