0

I'm looking to submit a form via an XHR but I'm having trouble getting a hold of the selected data to pass along.

<form>
    <select multiple id="select" >
        <option class="userOptions" value="1">Tyler Durden</option>
        <option class="userOptions" value="2">Robert Paulson</option>
        <option class="userOptions" value="3">Marla Singer</option>         
    </select>
</form>

What would be the best way to grab hold of the user selected values and pass them off to a page via an XHR?

I've tried things like document.getElementsByClassName("userOptions").selected but it's not returning anything. Also, should I pack this up as an array? Or is there a better way to send it? Thanks for your time!

1
  • Why don’t you just use jQuery’s serialize method (after giving the select element an appropriate name) …? Commented Dec 4, 2013 at 15:26

2 Answers 2

1

Here is a function in vanilla Javascript that will help you:

function getMultiValue(selectId)
{
    var list     = document.getElementById(selectId),
        selected = [],
        i;
    for (i = 0; i < list.options.length; i++) {
        if (list.options[i].selected) {
            selected.push(list.options[i].value);
        }
    }
    return selected;
}

In the case of your example, you must use this way:

var values = getMultiValue('select');

If you want those values converted to a query string:

var queryString = 'select=' + values.implode('&select=');

If the values contain special characters, you must do this before the construction of the query string:

var i;
for (i = 0; i < values.length; i++) {
    values[i] = escape(values[i]);
}

Or just change a little the previous function:

function getMultiValue(selectId, mustEscape)
{
    var list     = document.getElementById(selectId),
        selected = [],
        i;
    for (i = 0; i < list.options.length; i++) {
        if (list.options[i].selected) {
            selected.push(mustEscape ? escape(list.options[i].value) : list.options[i].value);
        }
    }
    return selected;
}

And use it this way:

var values      = getMultiValue('select', true),
    queryString = 'select=' + values.implode('&select=');
Sign up to request clarification or add additional context in comments.

Comments

0

Use jQuery and its just simple!

You can do it like this: http://jsfiddle.net/Hm2KL/

$("#sendbtn").click(function() {

    var data = $("#selectme").val();
    alert(data);

    $.ajax({
        url: ..,
        data: {data}
           etc..
    });

});

jQuery Ajax Doc: http://api.jquery.com/jQuery.ajax/

Comments

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.