您好我在stackoverflow上找到解决方案,通过单击父div选择复选框但是我正在寻找一个解决方案将选择限制为3.我找到了解决方案,分别用于限制复选框选择但不能合并两种解决方案。
请注意,我的复选框将不可见,用户可以通过单击div进行选择。但我需要将此选择限制为3。
<form role="form">
<div class="question">I’m Looking For / To:</div>
<div class="imageContainer" id="question-container-1">
<img src="bg.jpg" alt="">
<div class="text">
<label for="id_1">Label1</label>
<div class="l-right">
<input id="id_1" type="checkbox" name="id_1" value="Label1">
</div>
</div>
</div>
<div class="imageContainer" id="question-container-2">
<img src="bg.jpg" alt="">
<div class="text">
<label for="id_2">Label2</label>
<div class="l-right">
<input id="id_2" type="checkbox" name="id_2" value="Label1">
</div>
</div>
</div>
<div class="imageContainer" id="question-container-3">
<img src="bg.jpg" alt="">
<div class="text">
<label for="id_3">Label3</label>
<div class="l-right">
<input id="id_3" type="checkbox" name="id_3" value="Label1">
</div>
</div>
</div>
<div class="imageContainer" id="question-container-4">
<img src="bg.jpg" alt="">
<div class="text">
<label for="id_4">Label4</label>
<div class="l-right">
<input id="id_4" type="checkbox" name="id_4" value="Label1">
</div>
</div>
</div>
<button type="submit" class="btn">Save</button>
</form>
这里是jquery -
jQuery(function(){
// required for image checkboxes
jQuery('.imageContainer input:checkbox,.imageContainer label').bind("click",function(e) {
e.stopPropagation();
});
jQuery("div.imageContainer input:checkbox").bind("click",function(){
var imageContainerDiv = jQuery(this).closest("div.imageContainer");
var imageContainerInput = jQuery(this);
var triggerEl="";
imageContainer(imageContainerDiv,triggerEl);
});
jQuery("div.imageContainer").bind("click",function(){
var imageContainerDiv = jQuery(this);
var triggerEl=imageContainerDiv;
imageContainer(imageContainerDiv,triggerEl);
});
function imageContainer(imageContainerDiv,triggerElement){
var imageContainer=jQuery(imageContainerDiv).children("input:checkbox");
var imageCheckbox = jQuery(imageContainerDiv).find("input");
if(triggerElement==imageContainerDiv){
imageCheckbox.prop("checked", !imageCheckbox.prop("checked"));
}
jQuery(imageContainerDiv).toggleClass("ic-checked");
jQuery(imageContainerDiv).find("label").toggleClass("ic-selected");
}
//script required to limit only 3 checkbox to be selected.
var max = 3;
var checkboxes = jQuery('input[type="checkbox"]');
checkboxes.change(function(){
var current = checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
});
这是fiddle
答案 0 :(得分:0)
以下是您需要的伪代码: