Jay Corbett
Jay Corbett

Reputation: 28391

Using jQuery, how can I store the selected values of a select into an array?

Thanks for reading this.

I would have thought it would be as simple as using the .split function on the select .val(), but I get a js error. This is the code I am using. I will use .each() to loop through the selected items...but would like to understand what I am doing wrong...

If I set opts with a literal..the split works (commented code)

Thanks

<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/JavaScript">
$(function(){
    $("#multOpts").bind("click", function() {
    //  var opts = "OPT1,OPT2,OPT3" ;
        var opts = $("#select1").val() ;
        $("#text1").val(opts);
    });
    $("#oneOpt").bind("click", function() {
        //  var opts = "OPT1,OPT2,OPT3" ;
        var opts = $("#select1").val() ;
        var optsArray = opts.split(",") ;
        $("#text2").val("1st opt: " + optsArray[0]);
    });
}); // End eventlistener
</script>
</head><body>
<select id="select1" multiple size="5">
<option value="OPT1">Option 1</option>
<option value="OPT2">Option 2</option>
<option value="OPT3">Option 3</option>
<option value="OPT4">Option 4</option>
<option value="OPT5">Option 5</option>
</select>
<div>
<input id="multOpts" type="button" value="Show Options"/>
<input id="text1" type="text"/>
</div>
<input id="oneOpt" type="button" value="One Option"/>
<input id="text2"  type="text"/>
</body></html>

Upvotes: 1

Views: 5105

Answers (2)

GiDo
GiDo

Reputation: 1330

Since jQuery 1.2, .val() returns array of values is return on multiple select.

var opts = $("#select1").val() || [];
$("#text2").val("values is: " +opts.join(", "));

Upvotes: 1

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827208

The val() function when there are more than one option selected returns you already an array, you don't need to do the split.

    $("#oneOpt").bind("click", function() {
            var opts = $("#select1").val();
            $("#text2").val("1st opt: " + opts[0]);
    });

Upvotes: 6

Related Questions