简体   繁体   English

如果选中复选框,如何仅显示输入字段?

[英]How to only show input fields if checkbox is checked?

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 =) 任何建议将不胜感激=)

The "#foo" selector looks for elements whose id value is "foo", not "name". “#foo”选择器查找id值为“foo”的元素,而不是“name”。 Thus the first thing you need to do is add an "id" attribute to your checkbox. 因此,您需要做的第一件事是在复选框中添加“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. 需要担心的第二件事是,在IE(至少旧版本)中,只有在复选框元素失去焦点时才会触发“更改”事件。 It's better to handle "click", and what you want to check is the "checked" attribute of the element. 最好处理“click”,你要检查的是元素的“checked”属性。

What I'd write is something like: 我写的是:

$('#supplied').click(function() {
  $('.date')[this.checked ? "show" : "hide"]();
});

Pointy pointed out that you need to set the id of our checkbox (or use a name selector). Pointy指出你需要设置我们的复选框的id(或使用名称选择器)。 You also need to use #date (id) instead of .date (class) (or again change the HTML). 你还需要使用#date (ID),而不是.date (类)(或再次更改HTML)。

Working demo 工作演示

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中运行得很好。

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();
    }
});

Try this: 尝试这个:

$('input[name=supplied]').live('change', function(){
     if ( $(this).is(":checked")) {
         $('#date').show();
     } else {
         $('#date').hide();
     }
 });

Try something like: 尝试类似的东西:

$('#supplied').live('change', function(){
     if ( $(this).attr("checked")) {
         $('.date').show();
     } else {
         $('.date').hide();
     }
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM