SVK
SVK

Reputation: 2197

How to set selected value in multiple select list

Demo Link

Multi Select List:

<select id="fruits" name="fruits" multiple="multiple">
    <option value="1">Apple</option>
    <option value="2">Mango</option>
    <option value="3">Orange</option>
 </select>

Script Code:

var groups=["Apple","Orange"]; //Only Apple and orange values should be selected
$('#fruits').val(groups); 

Upvotes: 0

Views: 703

Answers (2)

Prakash
Prakash

Reputation: 576

Hope this helps you.

    var groups = ["Apple", "Orange"];

    $('#fruits').val(groups);

    $('select[name*="fruits"]').find('option').each(function() {
      var str = $(this).text()
      if (!contains(groups, str)) {
        $(this).prop('disabled', 'disabled');
      }
    });

    function contains(a, obj) {
      for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
          return true;
        }
      }
      return false;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="fruits" name="fruits" multiple="multiple">
  <option value="1">Apple</option>
  <option value="2">Mango</option>
  <option value="3">Orange</option>
</select>

Upvotes: 1

Satpal
Satpal

Reputation: 133453

You should set values correct. As of now you are passing the text not values.

var groups=[1,3];

var groups=[1,3];
$('#fruits').val(groups); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="fruits" name="fruits" multiple="multiple">
    <option value="1">Apple</option>
    <option value="2">Mango</option>
    <option value="3">Orange</option>
 </select>

However still you want to use texts i.e. ["Apple","Orange"];, .filter() method can be used along with .prop()

var groups = ["Apple", "Orange"];
$('#fruits option').filter(function() {
  return groups.indexOf($(this).text()) > -1; //Options text exists in array
}).prop('selected', true); //Set selected
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="fruits" name="fruits" multiple="multiple">
  <option value="1">Apple</option>
  <option value="2">Mango</option>
  <option value="3">Orange</option>
</select>

Upvotes: 3

Related Questions