选择多选选项限制最多2 [英] select multiselect option limit up to 2
问题描述
我正在对不同主题使用多重选择,如果用户取消选择,我想将选择限制为2个,并以相同的方式禁用另一个选择,同样,该选项必须对用户可用.
I am using multiselect for different subject's I want to limit the select up to 2 and make the other's disabled in the same way if user deselect, Again the option must be available for the user.
<select multiple="multiple" class="subjects" name="subjects[]" style="float:left;width:205px;" size="5">
<option value='1'>subject1</option>
<option value='2'>subject2</option>
<option value='3'>subject3</option>
<option value='3'>subject3</option>
</select>
到目前为止,我已经实现了仅取消选择2之后选择的最后一个选项,并且代码如下
So far I have achieved to deselect only the last option which was selected after 2 and the code is as follow
/**
* Make sure the subject's limit is 2
*/
$(".subjects option").click(function(e){
if ($(this).parent().val().length > 2) {
$(this).removeAttr("selected");
}
});
谢谢.
推荐答案
改进的jQuery示例,请注意(其他启用)选项,这修复了先前示例中的一个错误,该示例永久禁用了select选项.还删除了请仅选择两个选项".错误消息(如果可能). http://jsfiddle.net/c9CkG/25/
Improved jQuery example, notice the (else enable) option, this fixes a bug on previous examples that disabled the select options permanently. Also removed the "Please select only two options." error message when possible. http://jsfiddle.net/c9CkG/25/
jQuery(document).ready(function () {
jQuery("select").on("change", function(){
var msg = $("#msg");
var count = 0;
for (var i = 0; i < this.options.length; i++)
{
var option = this.options[i];
option.selected ? count++ : null;
if (count > 2)
{
option.selected = false;
option.disabled = true;
msg.html("Please select only two options.");
}else{
option.disabled = false;
msg.html("");
}
}
});
});
这篇关于选择多选选项限制最多2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!