javascript 在 HTML 中隐藏复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13299024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:21:06 来源:igfitidea点击:
Hiding a Check Box in HTML
提问by UndefinedReference
I have these two checkboxes:
我有这两个复选框:
<label for="cell">3. Do you currently have a cell phone? (Y/N)</label>
<input type="checkbox" name="cell" name="cell" id="cell" data-on="Yes" data-off="No" />
<label for="blackBerry">4.If YES, is the cell phone a BlackBerry? (Y/N)</label>
<input type="checkbox" name="blackBerry" name="blackBerry" id= "blackBerry" data-on="Yes" data-off="No" />
How can I get the second question to display on the page, ONLY when the first one is selected as Yes?
我怎样才能让第二个问题显示在页面上,只有当第一个问题被选择为是时?
Thanks in advance.
提前致谢。
回答by Sushanth --
You can do this using javascript
您可以使用 javascript 执行此操作
Javascript
Javascript
?var elem = ?document.getElementById('cell');
?elem.addEventListener('click', function() {
var divElem = document.getElementById('divPhone');
if( this.checked){
divElem.style.display = 'block' ;
}
else{
divElem.style.display = 'none' ;
}
});
HTML
HTML
<label for="cell">3. Do you currently have a cell phone? (Y/N)</label>
<input type="checkbox" name="cell" name="cell"
id="cell" data-on="Yes" data-off="No" />
<div id="divPhone" class="hidden">
<label for="blackBerry">4.If YES, is the cell phone a BlackBerry?
(Y/N)</label>
<input type="checkbox" name="blackBerry" name="blackBerry"
id= "blackBerry" data-on="Yes" data-off="No" />
</div>
?.hidden
{
display: none;
}?
?It is still more simple using jQuery..
?使用jQuery还是更简单..
?$('#cell').on('click', function() {
if(this.checked){
$('#divPhone').removeClass('hidden');
}
else{
$('#divPhone').addClass('hidden');
}
});?
回答by Niet the Dark Absol
CSS only:
仅 CSS:
<label for="cell">3. Do you currently have a cell phone? (Y/N)</label>
<input type="checkbox" name="cell" id="cell" data-on="Yes" data-off="No" />
<div class="hide_if_no">
<label for="blackBerry">4. If YES, is the cell phone a BlackBerry? (Y/N)</label>
<input type="checkbox" name="blackBerry" id="blackBerry" data-on="Yes" data-off="No" />
</div>
CSS:
CSS:
input[type=checkbox] ~ div.hide_if_no {display:none}
input[type=checkbox]:checked ~ div.hide_if_no {display:block}
回答by keithxm23
With jQuery,
使用 jQuery,
$('#cell').change(function() {
var c = this.checked;
if (c) {
$("#blackBerry").show();
} else {
$("#blackBerry").hide();
}
});?