2015-09-18 107 views
0

如何在有限复选框被选中后禁用复选框? 我想创建两种不同的形式,其中第一种形式的用户只能选中3个复选框,其余的复选框应该被禁用,而在第二种形式中只能选择两个复选框,其余的应该禁用。使用Jquery禁用复选框

+5

你尝试过什么吗?你能告诉我们你到底在哪里挣扎吗? –

+0

http://stackoverflow.com/questions/2330209/jquery-checkbox-enable-disable检查它 – m2j

+1

@priya:我希望你的问题得到解决,请标记答案无论哪个答案帮助你。所以,它可以帮助别人。 –

回答

2

这里有一个简单的代码片段,应该可以做你想做的。只需调整表单上的自定义属性data-checksallowed,它应该处理任意数量的允许复选框。

$('[data-checksallowed]').on("change", 'input[type="checkbox"]', function() { 
 
    var parent = $(this).closest("[data-checksallowed]"); 
 
    var checksallowed = parent.data('checksallowed'); 
 
    var checkboxes = parent.find('input[type="checkbox"]'); 
 
    var checkedboxes = checkboxes.filter(':checked'); 
 
    var uncheckedboxes = checkboxes.not(checkedboxes); 
 
    
 
    if (checkedboxes.length == checksallowed) 
 
    uncheckedboxes.prop('disabled', true); 
 
    else 
 
    uncheckedboxes.prop('disabled', false); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<form data-checksallowed="3"> 
 
    <input type="checkbox" /> 
 
    <input type="checkbox" /> 
 
    <input type="checkbox" /> 
 
    <input type="checkbox" /> 
 
    <input type="checkbox" /> 
 
</form> 
 
<form data-checksallowed="2"> 
 
    <input type="checkbox" /> 
 
    <input type="checkbox" /> 
 
    <input type="checkbox" /> 
 
    <input type="checkbox" /> 
 
    <input type="checkbox" /> 
 
</form>

+0

@priya你为什么不接受这个答案?有什么不适合你吗? – dave

1

像这样的事情会为你工作。

<div id="chks"> 
<input type="checkbox" value="1" /> 1 
<input type="checkbox" value="2" /> 2 
<input type="checkbox" value="3" /> 3 
<input type="checkbox" value="4" /> 4 
<input type="checkbox" value="5" /> 5 
<input type="checkbox" value="6" /> 6 
<input type="checkbox" value="7" /> 7 
<input type="checkbox" value="8" /> 8 
</div> 

JavaScript的将是这样的:

$('#chks input[type="checkbox"]').click(function(){ 
    // get the count of all checked boxes 
    var cnt = $('#chks input[type="checkbox"]:checked').length; 
    if(cnt == 3){ 
     // if cnt is equal to 3 disable all checkboxes that are NOT checked 
     // you want to leave the checked ones enabled 
     $('#chks input[type="checkbox"]').not(':checked').attr('disabled', 'disabled'); 
    }else{ 
     // if count is not equal to 3 make sure the unchecked are enabled 
     // count should never be more than 3 because this will disable them 
     $('#chks input[type="checkbox"]').not(':checked').removeAttr('disabled'); 
    } 

});