[英]Select only one checkbox for toggling a set of divs
ok, I have a set of 3 divs which are toggled to show/hide based on a checkbox selection, my issue is I only want one checkbox at a time to be selected好的,我有一组 3 个 div,可以根据复选框选择来切换显示/隐藏,我的问题是我一次只希望选择一个复选框
This is the checkbox used to toggle这是用于切换的复选框
<input onClick="toggle('village');" type="checkbox" style="transform: scale(1.5);"><label> Only Villages</label>
This is the code that toggles the divs这是切换 div 的代码
function toggle(matchingAttribute) {
// optain all div elements in the page
var divArray = document.getElementsByTagName("div");
for(i=divArray.length-1; i>=0; i--) { // for each div
if(divArray[i].id.match("_"+matchingAttribute+"_")) {
if(divArray[i].style.display != 'none') {
divArray[i].style.display = 'none';
}
else {
divArray[i].style.display = '';
}
}
}
}
Any help gratefully received感激地收到任何帮助
at first unchecked all checkbox then checked this checkbox首先取消选中所有复选框然后选中此复选框
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == "checkbox") {
inputs[i].checked = false;
}
}
this.checked = true;
I've created a JSFiddle for you as an example, which fulfills what your requirement is.我已经为您创建了一个JSFiddle作为示例,它满足您的要求。
Script:脚本:
$('input[type="checkbox"]').click(function(){
var inputValue = $(this).attr("value");
if (this.checked)
{
$('input:checkbox').removeAttr('checked');
$(".red").hide();
$(".green").hide();
$(".blue").hide();
$("." + inputValue).show();
$(this).prop("checked", true);
}
else
{
$(".red").hide();
$(".green").hide();
$(".blue").hide();
}
});
HTML: HTML:
<div>
<label><input type="checkbox" name="colorCheckbox" value="red"> red</label>
<label><input type="checkbox" name="colorCheckbox" value="green"> green</label>
<label><input type="checkbox" name="colorCheckbox" value="blue"> blue</label>
</div>
<div class="red box">You have selected <strong>red checkbox</strong> so i am here</div>
<div class="green box">You have selected <strong>green checkbox</strong> so i am here</div>
<div class="blue box">You have selected <strong>blue checkbox</strong> so i am here</div>
Do let me know if you need anything else.如果您需要其他任何东西,请告诉我。
Hope it helps :)希望能帮助到你 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.