如何防止在运行代码时不勾选复选框? 我有一些带有复选框的div,并且想要检查每个内部的checkbex并同时隐藏特定的div,但是当我运行它时,会检查所有复选框:
HTML:
<input type="checkbox" id="hide-and-checked">group 1
<div id="one" class="hide-and-checked">
<input type="checkbox" class="list_check" value="1">1
<input type="checkbox" class="list_check" value="2">2
<input type="checkbox" class="list_check" value="3">3</div>
<br>
<input type="checkbox" id="hide-and-checked">grup 2
<div id="two" class="hide-and-checked">
<input type="checkbox" class="list2" value="1">1
<input type="checkbox" class="list2" value="2">2</div>
JS:
$(document).ready(function () {
function toggleDiv() {
var $this = $(this);
$("." + $this.attr('id'))[$this.is(':checked') ? 'hide' : 'show']();
$(":checkbox").each(
function () {
$(this).attr('checked', true);
});
}
$('input:checkbox').each(toggleDiv).click(toggleDiv);
});
答案 0 :(得分:1)
<input type="checkbox" id="hide-and-checked" checked="true" /> group 1
<div id="one" class="hide-and-checked" >
<input type="checkbox" class="list_check" value="1"/>1
<input type="checkbox" class="list_check" value="2"/>2
<input type="checkbox" class="list_check" value="3"/>3
</div>
<br />
<input type="checkbox" id="hide-and-checked"/> grup 2
<div id="two" class="hide-and-checked">
<input type="checkbox" class="list2" value="1"/>1
<input type="checkbox" class="list2" value="2"/>2
</div>
脚本
$(document).ready(function() {
$('input[id="hide-and-checked"]').each(function(){
$(this).change(function(){toggleOperation(this)});
toggleOperation(this);
});
function toggleOperation(ctrl)
{
var $this = $(ctrl);
if($this.is(':checked'))
{
$this.next().find(":checkbox").attr("checked",true);
$this.next().show();
}
else
{
$this.next().hide(); $this.next().find(":checkbox").attr("checked",false);
}
}
});
在下面的链接中尝试此代码
答案 1 :(得分:0)
首先查看问题的灵感来建议event.preventDefault()
因为“防止复选框被检查......”。我后来一遍又一遍地读它,我明白你想要的东西与众不同。 “检查并隐藏”前进的步骤。我为这个问题准备了demo at jsFiddle。
'上方复选框'控制'子复选框',其中包含:
$("input.upper-box").on("change", function() {
var $this = $(this);
$this.next("div.sub-group")
.find(":checkbox")
.prop("checked", $this.prop("checked"))
.end()
.toggle("slow");
});
关于jquery团队建议的复选框的一点注意事项是,如果您定位($ 1.6 +),则应使用prop()
而不是attr()
。
答案 2 :(得分:0)
Try this
jsfiddle.net/Subhash09/8k2HK/10/