Javascript 如果选中复选框,如何仅显示输入字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5137302/
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
How to only show input fields if checkbox is checked?
提问by Latox
Basically, I want to only show these fields if checkbox is selected, if it becomes unselected, disappear.
基本上,我只想在选中复选框时显示这些字段,如果未选中,则消失。
<input type="checkbox" name="supplied" value="supplied" class="aboveage2" />
<ul id="date">
<li><input id="start" name="start" size="5" type="text" class="small" value="1" /></li>
<li><input id="end" name="end" size="5" type="text" class="small" value="2" /></li>
</ul>
I've tried something like:
我试过这样的事情:
$('#supplied').live('change', function(){
if ( $(this).val() === 'supplied' ) {
$('.date').show();
} else {
$('.date').hide();
}
});
Any advice would be greatly appreciated =)
任何建议将不胜感激 =)
回答by Pointy
The "#foo" selector looks for elements whose idvalue is "foo", not "name". Thus the first thing you need to do is add an "id" attribute to your checkbox.
"#foo" 选择器查找id值为 "foo" 而不是 "name" 的元素。因此,您需要做的第一件事是在复选框中添加“id”属性。
The second thing to worry about is the fact that, in IE (at least old versions), the "change" event isn't fired until the checkbox element loses focus. It's better to handle "click", and what you want to check is the "checked" attribute of the element.
需要担心的第二件事是,在 IE(至少是旧版本)中,直到复选框元素失去焦点才会触发“更改”事件。处理“click”比较好,你要检查的是元素的“checked”属性。
What I'd write is something like:
我会写的是这样的:
$('#supplied').click(function() {
$('.date')[this.checked ? "show" : "hide"]();
});
回答by Matthew Flaschen
Pointy pointed out that you need to set the id of our checkbox (or use a name selector). You also need to use #date
(id) instead of .date
(class) (or again change the HTML).
Pointy 指出您需要设置我们复选框的 id(或使用名称选择器)。您还需要使用#date
(id) 而不是.date
(class) (或再次更改 HTML)。
回答by kojiro
You can do this with pure CSS3, of course:
当然,您可以使用纯 CSS3 做到这一点:
:checked + #date { display: block; }
#date { display: none; }
The equivalent selectors ought to work just fine in jQuery as well.
等效的选择器在 jQuery 中也应该可以正常工作。
回答by Bryan McRee
Matthews answer works great just that the .live deprecated in jQuery 1.7 use the .on
Matthews 的回答非常有效,只是 jQuery 1.7 中不推荐使用的 .live 使用了 .on
$('#supplied').on('change', function(){
if ( $(this).is(':checked') ) {
$('#date').show();
} else {
$('#date').hide();
}
});
回答by Chandu
Try this:
尝试这个:
$('input[name=supplied]').live('change', function(){
if ( $(this).is(":checked")) {
$('#date').show();
} else {
$('#date').hide();
}
});
回答by Rob
Try something like:
尝试类似:
$('#supplied').live('change', function(){
if ( $(this).attr("checked")) {
$('.date').show();
} else {
$('.date').hide();
}
});