jas
jas

Reputation: 1582

How to set multiple select values from string using Jquery

I have a span Id with some values that correspond to values in multiple select box items. I want to take the values from span Id and select the corresponding items in list.

<span id="test">
  1,4
</span>
<select id='multipleSelect' multiple='multiple'>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

I can read the string into array but not sure how to use array to select items in multiple Select box

var test = $("#test").text();
var testArray = test.split(',');

I guess if the values are known then it is easy to do something like this

$('#multipleSelect').val(['1', '2']);

Here is JS fiddle to illustrate the idea so far https://jsfiddle.net/deu8ftpb/1/

Upvotes: 1

Views: 16943

Answers (3)

ronkpunk
ronkpunk

Reputation: 11

maybe a bit late.

You have to trim value in array.

In your case, I resolved using .map and trimming values

var test = $.trim($("#test").text());
var testArray = test.split(',');
var testArray = testArray.map(function(item){ return item.trim(); });
$('#multipleSelect').val(testArray);

I had a similar case but my "testArray" was an integer array (instead of strings like your testArray was). In my case I had to use .map for converting value from integer to strings.

Upvotes: 0

Rakesh Sojitra
Rakesh Sojitra

Reputation: 3658

try this code. You just missing trim() that texts and put splitted array as val()

var test = $.trim($("#test").text());
var testArray = test.split(',');
$('#multipleSelect').val(testArray);

Upvotes: 4

TheWandererr
TheWandererr

Reputation: 514

You did everything right. You only forgot to set the val for the select. Like so: $('#multipleSelect').val(testArray);

Upvotes: 0

Related Questions