如何在多个选择列表

时间:2015-12-17 06:37:49

标签: javascript jquery

Demo Link

多选列表:

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

脚本代码:

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

2 个答案:

答案 0 :(得分:3)

您应该将value设置为正确。截至目前,您传递的文字不是值。

var groups=[1,3];

&#13;
&#13;
var groups=[1,3];
$('#fruits').val(groups); 
&#13;
<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>
&#13;
&#13;
&#13;

但是您仍然希望使用["Apple","Orange"];.filter()方法可以与.prop()

一起使用

&#13;
&#13;
var groups = ["Apple", "Orange"];
$('#fruits option').filter(function() {
  return groups.indexOf($(this).text()) > -1; //Options text exists in array
}).prop('selected', true); //Set selected
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

希望这会对你有所帮助。

&#13;
&#13;
    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;
    }
&#13;
<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>
&#13;
&#13;
&#13;