9

How can I get the .val()'s and .html()'s of all the options from a multiple select list into a json object? Preferably using jQuery.

Thanks in advance!

A little more info:

I am using two multiple select boxes. Selecting items on the left box and moving them to the right. Once they have all the items they want selected they will push submit and it will take all the items in the right select box and move them to a main list.

Here is the code I am using once I get the JSON object:

datalistObject = JSON.parse(response);
if (datalistObject.length){
    $(".data-list tbody").empty();
    for (var i=0; i < datalistObject.length; i++) {
        var newrow = "<tr><td><input type='checkbox' name='user_id' value='" + datalistObject[i][0] + "' class='data-list-check'></td><td>" + datalistObject[i][1] + "</td></tr>";
        $(newrow).appendTo($(".data-list tbody"));
    }
}

Example html and output would be:

<select name="selecteditems">
    <option value="op1">Option 1</option>
    <option value="op2">Option 2</option>
    <option value="op3">Option 3</option>
</select>

[
    ["op1","Option 1"],
    ["op2","Option 2"],
    ["op3","Option 3"]
]
3
  • All the selected options, or all items? Commented Dec 1, 2010 at 17:19
  • Why do you need it in a JSON object? If you give a little more information as to what you are trying to achieve, it will get you better answers. Commented Dec 1, 2010 at 17:19
  • Please give example html and json output. Commented Dec 1, 2010 at 17:20

1 Answer 1

14

Something like this?

var items = $("#select > option").map(function() {
    var opt = {};
    opt[$(this).val()] = $(this).text();
    return opt;
}).get();

for(var i = 0; i < items.length; i++) {
    for(key in items[i]) {
        alert(key + ': ' + items[i][key]);   
    }
}

Demo: http://jsfiddle.net/eNGUL/

EDIT: To get a structure like your example data:

var items = $("#select > option").map(function() {
    var arr = [];
    arr.push([$(this).val(), $(this).text()]);
    return arr;
}).get();
for(var i = 0; i < items.length; i++) {
    alert(items[i]);
}

Demo: http://jsfiddle.net/karim79/eNGUL/2/

See .map.

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

2 Comments

Can you explain this a little bit? I've never used the map method. How could I get the output that I specified above? Thanks!
@RandyLahey - I've edited my answer. If you read the doc page for .map and look at the examples I think you'll get it, it is fairly straightforward.

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.