当用户从多选选项中选择了一定数量的值时,我试图取消选择多选选项元素的最后一个选项。这是我的jquery代码,当用户尝试选择第3个选项时,它会取消选择所有选定的选项。但我想取消选择第三个。
$(document).ready(function() {
$("select#connection_profiles").change(function() {
if ($("select#connection_profiles option:selected").length > 2) {
$("#connection_profiles").val([]);
alert('You can only select a max of 2 connection profile.');
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="input-group"><span class="input-group-addon">Server</span>
<select class="form-control" multiple name="connection_profiles[]" id="connection_profiles">
<option value=''>Please select max of 2 connection profile</option>
<option value='10'>Rackware Cloud Server</option>
<option value='8'>Rackspace Cloud Server</option>
<option value='9'>Mitel MiCloud Cloud Server</option>
<option value='7'>Carbonite Cloud Server</option>
<option value='6'>Steam Gaming Cloud Server</option>
<option value='5'>Microsoft Exchange Cloud Server</option>
</select>
</div>
</div>
&#13;
答案 0 :(得分:1)
var prevOpts = [];
$("select#connection_profiles").change(function() {
var val = $(this).val();
if (val.length > 2) {
$(this).val(prevOpts);
alert('You can only select a max of 2 connection profile.');
} else {
prevOpts = val;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Server</span>
<select class="form-control" multiple name="connection_profiles[]" id="connection_profiles">
<option value=''>Please select max of 2 connection profile</option>
<option value='10'>Rackware Cloud Server</option>
<option value='8'>Rackspace Cloud Server</option>
<option value='9'>Mitel MiCloud Cloud Server</option>
<option value='7'>Carbonite Cloud Server</option>
<option value='6'>Steam Gaming Cloud Server</option>
<option value='5'>Microsoft Exchange Cloud Server</option>
</select>
</div>
</div>
每次下拉列表更改时,代码都会检查其值是否超过2个元素(jQuery返回多个下拉列表的数组)。如果是,它将在您选择第3个元素(prevOpts变量)之前将下拉值设置为其先前的值,否则它会将prevOpts变量设置为所选的值。