So I have a few lists of checkboxes, all with the a slightly different class of single-check with a number on the end indicating which list they're in, since I'm not using radio buttons. How would I go about making it so that any checkbox that is in the same class can't be checked if another checkbox in that class is already checked?
所以我有一些复选框列表,所有这些都有一个稍微不同的单一检查类,最后一个数字表示它们所在的列表,因为我没有使用单选按钮。如果已经检查了该类中的另一个复选框,我将如何制作它以便无法检查同一类中的任何复选框?
Thanks
2 个解决方案
#1
2
Using jQuery.not
when a checkbox is clicked, you could set the checked
property on all the other checkboxes in that group, to false
(meaning they won't be checked).
单击复选框时使用jQuery.not,可以将该组中所有其他复选框上的checked属性设置为false(表示不会检查它们)。
$(function() {
$(".myCheckboxInGroup1").on("click", function() {
$(".myCheckboxInGroup1").not(this).prop("checked", false);
});
});
#2
0
function howtoreadresults(){
var r = [];
$('input[type=checkbox]:checked').each(function(i,o){
r.push($(o).attr('group')+'='+$(o).val());
});
return r;
}
$('input[type=checkbox]').change(function(e){
$('[group='+$(this).attr('group')+']:checked').not($(this)).prop('checked',false);
console.log(howtoreadresults());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<input type='checkbox' group='cars' value='red' />
<input type='checkbox' group='cars' value='blue' />
<input type='checkbox' group='cars' value='green' />
<input type='checkbox' group='bike' value='red' />
<input type='checkbox' group='bike' value='blue' />
<input type='checkbox' group='bike' value='green' />
#1
2
Using jQuery.not
when a checkbox is clicked, you could set the checked
property on all the other checkboxes in that group, to false
(meaning they won't be checked).
单击复选框时使用jQuery.not,可以将该组中所有其他复选框上的checked属性设置为false(表示不会检查它们)。
$(function() {
$(".myCheckboxInGroup1").on("click", function() {
$(".myCheckboxInGroup1").not(this).prop("checked", false);
});
});
#2
0
function howtoreadresults(){
var r = [];
$('input[type=checkbox]:checked').each(function(i,o){
r.push($(o).attr('group')+'='+$(o).val());
});
return r;
}
$('input[type=checkbox]').change(function(e){
$('[group='+$(this).attr('group')+']:checked').not($(this)).prop('checked',false);
console.log(howtoreadresults());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<input type='checkbox' group='cars' value='red' />
<input type='checkbox' group='cars' value='blue' />
<input type='checkbox' group='cars' value='green' />
<input type='checkbox' group='bike' value='red' />
<input type='checkbox' group='bike' value='blue' />
<input type='checkbox' group='bike' value='green' />