user2227904
user2227904

Reputation: 679

Change selected items of a multiselect

I have a big multiselect list from which I want to get all options, deselect them and select new ones based on predefined criteria.

For example

<select>
  <option value='1' selected></option>
  <option value='2'></option>
  <option value='3'></option>
  <option value='4' selected></option>
</select>

I receive from request that the selects must be 2 and 4 for example. The question is how can I select 2 and 4 and deselect all others so that it may work fast and efficiently (Consider that this will have thousands of rows of data)

 $("select").val("2");

I thought of this, but it works just for one value as far as I know. Any help with this will be appreciated.

Upvotes: 0

Views: 215

Answers (2)

Paul Roub
Paul Roub

Reputation: 36458

You'll need to find the appropriate options and select them:

$('#foo > option').
  prop('selected', false).             // deselect by default
  filter("[value='2'],[value='4']").   // find our matches
  prop('selected', true);              // select them
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="foo" multiple>
  <option value='1' selected>1</option>
  <option value='2'>2</option>
  <option value='3'>3</option>
  <option value='4' selected>4</option>
</select>

Upvotes: 1

Colin DeClue
Colin DeClue

Reputation: 2244

First you need to set your select to be multi-selectable:

<select multiple id='select'>
  <option value='1' selected>1</option>
  <option value='2'>2</option>
  <option value='3'>3</option>
  <option value='4' selected>4</option>
</select>

Next, you can select all of the selected options, and unselect them:

$('#select').find("option:selected").prop("selected", false);

Finally, you select the ones you DO want to be selected, and set them to be selected:

$('#select').find("option[value='2'], option[value='4']").prop("selected", true);

Snippet:

$('#select').find("option:selected").prop("selected", false);
$('#select').find("option[value='2'], option[value='4']").prop("selected", true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id='select'>
  <option value='1' selected>1</option>
  <option value='2'>2</option>
  <option value='3'>3</option>
  <option value='4' selected>4</option>
</select>

Upvotes: 1

Related Questions