【问题标题】:Show/hide div based on checkbox value根据复选框值显示/隐藏 div
【发布时间】:2013-01-29 18:27:53
【问题描述】:

当用户选中“学生”时(check-1)。 2 个复选框值应该消失并显示一个文本输入 div。截至目前,我已将输入显示记录下来。但我似乎无法让复选框消失。

我试过了:

$(function () {
  $('#check-1').change(function () {                
      $('.name').toggle(this.checked);
      $('#check-1').hide();
      $('#check-2').hide();
  }).change();
});

但这不起作用。选中“学生”后如何隐藏复选框?有什么想法吗?

这是一个小的fiddle。提前感谢您的帮助。

【问题讨论】:

  • 为什么要隐藏both
  • 您隐藏了复选框,但没有隐藏标签。 (这是你要问的吗?)

标签: javascript jquery


【解决方案1】:

请看下面的代码:

$(".my-check").change(function() {
    if ( $(this).is(':checked') ) {
        $(".my-box").show();
    } else {
        $(".my-box").hide();
    }
});

更多详情见: http://jsfiddle.net/marloscarmo/vMFQd/

【讨论】:

    【解决方案2】:

    用 div 包裹你的文本框,说“thisWrapper”

    <div id="thisWrapper">
        <input type="checkbox" id="check-1" class="checkchoice staff" required><label for="check-1" class="choice staff">Staff</label>
        <input type="checkbox" id="check-2" class="checkchoice student" required><label for="check-2" class="choice student">Student</label>
    </div>
    

    并在您发布的更改事件中添加:

      $("thisWrapper").hide();
    

    应该同时隐藏两个复选框。当然,您必须添加“取消”或“重置”按钮才能再次显示复选框。

    或者你可以给复选框一个新的类名,比如“mycheckboxes”,然后调用它:

    $(".mycheckboxes").click(function() {
            $('#check-1').hide();
    $("#check-2").hide();
    });
    

    * 这是我在 FIDDLER 中工作的完整示例 **

    试试这个:

    <div id="thisWrapper">
        <input type="checkbox" id="check-1" class="checkchoice" required><label for="check-1" class="choice staff">Staff</label>
        <input type="checkbox" id="check-2" class="checkchoice" required><label for="check-2" class="choice student">Student</label>
    </div>
    <div id="nameinput">
        <input type="text" placeholder="So what's your name?" />
    </div>
    
    <script>
        $(function() {
    
           $(".checkchoice").change(function() {
                  $("#thisWrapper").hide();
                   $("#nameinput").show();
           });
    
        });
    </script>
    

    【讨论】:

    • 我尝试了你的建议。但似乎一切都消失了。
    • 哦,抱歉,我以为你想隐藏标签。试试这个: $("#check-2").click(function() { $('#check-1').hide(); $('#check-2').hide(); }
    • 看看我上面的代码 - 如果你复制和粘贴它在 fiddler 中工作 - 抱歉我不经常使用 fiddler 哈哈
    • 这似乎对我不起作用。我错过了什么fiddle here ..(忘记透露)
    • 太棒了。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 2016-09-04
    相关资源
    最近更新 更多