我正在尝试为多个选择框设置最小和最大选择值.
我在这里看到类似的单选按钮列表(仅限于最大值)
http://jsfiddle.net/rREfg/1/
var maxCheckedCount = 5;
var maxCheckedAlertMessage = 'Woops! Too many selected!';
jQuery('input[type=checkbox]').click(function(){
var n = jQuery('input:checked').length;
if(n>=maxCheckedCount){
jQuery(this).prop('checked',false);
alert(maxCheckedAlertMessage);
}
});
现在,如果这是我的新HTML
<select multiple size=7>
<option value="1">Strawberry</option>
<option value="2">Prune</option>
<option value="3">Lemon</option>
<option value="4">Peach</option>
<option value="5">Apple</option>
<option value="6">Banana</option>
<option value="7">Orange</option>
</select>
如何调整代码以获得最小选择2项和最多选择5项?
最佳答案 你可以像这样实现它
HTML
<select multiple size=7>
<option value="1">Strawberry</option>
<option value="2">Prune</option>
<option value="3">Lemon</option>
<option value="4">Peach</option>
<option value="5">Apple</option>
<option value="6">Banana</option>
<option value="7">Orange</option>
</select>
jQuery的
var maxCheckedCount = 5;
var maxCheckedAlertMessage = 'Woops! Too many selected!';
jQuery('select').change(function(event) {
var n = $(this).children(':selected').length;
if(n >= maxCheckedCount){
$(this).children().prop('selected',false);
alert(maxCheckedAlertMessage);
return false;
}
});
jQuery('.checkValid').click(function()
{
if($('select').children(':selected').length <= 2) {
alert('Keep Adding');
return false;
}
});
var maxCheckedCount = 5;
var maxCheckedAlertMessage = 'Woops! Too many selected!';
jQuery('select').change(function(event) {
var n = $(this).children(':selected').length;
if(n >= maxCheckedCount){
$(this).children().prop('selected',false);
alert(maxCheckedAlertMessage);
n = maxCheckedCount;
return false;
}
});
jQuery('.checkValid').click(function()
{
if($('select').children(':selected').length <= 2) {
alert('Keep Adding');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple size=7>
<option value="1">Strawberry</option>
<option value="2">Prune</option>
<option value="3">Lemon</option>
<option value="4">Peach</option>
<option value="5">Apple</option>
<option value="6">Banana</option>
<option value="7">Orange</option>
</select>
<button class='checkValid'>Clike Me!</button>