1

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>

2 Answers 2

6

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]);
    });
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

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.