如何在选中复选框时切换文本并在未选中任何内容时隐藏
how to toggle text when checkbox(es) are checked and hide when nothing is checked
选中复选框时,会显示文本 Checked
。取消选中所有复选框时,如何隐藏文本 Checked
?
$('.rafcheckbox').click(function() {
$(".rafoptions").show();
});
<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />
<div class="rafoptions" style="display:none">Checked</div>
要完成这项工作,您可以使用 :checked
选择器和 length
属性 来确定是否选中 any 个框.然后你可以根据需要使用toggle()
到hide/show div
。
var $checkboxes = $('.rafcheckbox').change(function() {
var anyChecked = $checkboxes.filter(':checked').length != 0;
$(".rafoptions").toggle(anyChecked);
});
.rafoptions { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />
<div class="rafoptions">Checked</div>
您可以使用在 ES6
中引入的 every()
来实现此目的
$(".rafcheckbox").click(function() {
let checkedInputs = [];
$(".rafcheckbox").each(function() {
checkedInputs.push(this.checked)});
if(checkedInputs.every(element => !element))
$(".rafoptions").hide();
else
$(".rafoptions").show();
});
选中复选框时,会显示文本 Checked
。取消选中所有复选框时,如何隐藏文本 Checked
?
$('.rafcheckbox').click(function() {
$(".rafoptions").show();
});
<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />
<div class="rafoptions" style="display:none">Checked</div>
要完成这项工作,您可以使用 :checked
选择器和 length
属性 来确定是否选中 any 个框.然后你可以根据需要使用toggle()
到hide/show div
。
var $checkboxes = $('.rafcheckbox').change(function() {
var anyChecked = $checkboxes.filter(':checked').length != 0;
$(".rafoptions").toggle(anyChecked);
});
.rafoptions { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />
<div class="rafoptions">Checked</div>
您可以使用在 ES6
中引入的every()
来实现此目的
$(".rafcheckbox").click(function() {
let checkedInputs = [];
$(".rafcheckbox").each(function() {
checkedInputs.push(this.checked)});
if(checkedInputs.every(element => !element))
$(".rafoptions").hide();
else
$(".rafoptions").show();
});