禁止在多个选择选项中删除最后一个值-select2

时间:2019-07-11 07:10:50

标签: javascript jquery jquery-select2

选定的option来自数据库。现在我想要,我可以删除任何两个值,但不能删除最后一个值。我已经尝试过disabled: true,但不知道如何限制不删除姓氏。预先感谢。

$(document).ready(function(){
    $("#test").select2({
      tags: true,
      tokenSeparators: [',', ' ']
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
    
<select id="test" multiple style="width:250px" name="lastname">
  <option value="1" selected="selected">One</option>
  <option value="2" selected="selected">Two</option>
  <option value="3" selected="selected">Three</option>
</select>

2 个答案:

答案 0 :(得分:2)

这应该为您工作。有关更多此类事件,请参考official documentation

$(document).ready(function(){
    $("#test").select2({
      tags: true,
      tokenSeparators: [',', ' ']
    });
    $('#test').on("select2:unselecting", function (e) {
      if($(this).val().length === 1) {
        alert("You cannot remove last value");
        e.preventDefault();
      }
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
    
<select id="test" multiple style="width:250px" name="lastname">
  <option value="1" selected="selected">One</option>
  <option value="2" selected="selected">Two</option>
  <option value="3" selected="selected">Three</option>
</select>

答案 1 :(得分:1)

我已经尝试了一些代码,这可能很好用

$(document).ready(function(){
let prevVal = $('#test').val();
$("#test").select2({
  tags: true,
  allowClear: false,
  tokenSeparators: [',', ' ']
}).on("change", function (e) { 
    if($("#test").val() !== null){
        prevVal = $('#test').val();
    }
    else{
        $('#test').val(prevVal)
        $('#test').trigger('change.select2')
    }
});});