1

I managed to select all of the options from a multiselect, however, I am trying to select Test2 and Test3 only. I have an array $arr which contains some values I want to select. for example $arr = ('Test2', 'Test3')

<select id="test" multiple="multiple">
    <option>Test</option>
    <option>Test2</option>
    <option>Test3</option>
    <option>Test4</option>
</select>

Selecting all:

$('#test option').attr('selected', 'selected');
3
  • use index to select like $('#test option:nth-child(2)').attr('selected', 'selected'); $('#test option:nth-child(3)').attr('selected', 'selected'); Commented Sep 21, 2017 at 1:57
  • I need to select based on the value not the index Commented Sep 21, 2017 at 1:57
  • var multi = $('#test').val(), two = multi[1], three = multi[2]; console.log(two); console.log(three); Commented Sep 21, 2017 at 2:01

2 Answers 2

1

Try something like this.

var selOptions = ['Test2', 'Test3'];
$('#test option').each(function() {
//this is the option. If attribute value isn't set explicitly then test is the value
  if (selOptions.indexOf(this.value) > -1)
    this.selected = 1;
});
console.log($('#test option:selected'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="test" multiple="multiple">
    <option>Test</option>
    <option>Test2</option>
    <option>Test3</option>
    <option>Test4</option>
</select>

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

Comments

0

Have you tried the using ":contains" to target the text itself?

$('#test option:contains("Test2"), #test option:contains("Test3")').attr('selected', 'selected');

Edit:

If you literally want the 2nd and 3rd option regardless of the text, you can use a child selector like so..

$('#test option:nth-child(2), #test option:nth-child(3)').attr('selected', 'selected');

4 Comments

I just dont want to hard code the values, as my values are in an array
I see.. I added a simple child selector option ;)
Thanks, but I dont know the index of the values
Then you need to rephrase your question. As well as add more information. As it stands, I don't even know what you're asking for.

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.