1

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/

2
  • 2
    You were very close to solution $('#multipleSelect').val($("#test").text().trim().split(',')); jsfiddle.net/8621wujp Commented Sep 28, 2016 at 12:36
  • jsfiddle.net/suyesht/deu8ftpb/3 Check this updated fiddle. Commented Sep 28, 2016 at 12:42

3 Answers 3

4

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

2 Comments

$.trim only removed the space around the first string. It works fine after using replace(/\s/g, "")
The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. Refer api.jquery.com/jQuery.trim
0

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

Comments

0

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.

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.