简体   繁体   中英

Show / hide nested checkbox labels

I'm trying to make a nested label/checkbox visible when its containing label/checkbox is checked. I can't figure out how to target the specific nested label or if this is even the right way to do it.

Here's a fiddle:

http://jsfiddle.net/kirkbross/tfKva/15/

Here's the javascript:

$(".label-1").click(function() {
    $("input:checkbox").each(function() {
        if ($(this).prop("checked")) {
            $(this).next('.label-2').show(); // can't figure out how to get at the second "nested" label

        } else {
            $(this).next('.label-2').hide();
        }
    });
});

.show() doesn't display element if you have used visibility:hidden;

I will suggest you to use

  style="display:none;" 

instead of

 style="visibility:hidden;"

DEMO

A few thoughts on this:

  • Your html could be a little better structured by not nesting multiple controls inside of a label (this will cause issues if you use the html for attribute properly).
  • Sometimes it is easier to read css classes than use inline styles (what hide() and show() actually do)

That in mind, I would suggest the following. JSFIDDLE : http://jsfiddle.net/SaHGs/

HTML

<div class="check-container">
  <label for="label1">This is label 1</label>
  <input type="checkbox" id="label1" class="hideshow" />

  <div class="autohide checkhidden">
    <label for="label2">This is label 2</label>
    <input type="checkbox" id="label2" />
  </div>
</div>

Javascript

$(function () {
  $(".hideshow").click(function(args) {
    var showStuff = $(this).prop("checked");
    $(this).parent().find(".autohide").each(function () {
      if (showStuff)
        $(this).removeClass("checkhidden");
      else
        $(this).addClass("checkhidden");
    });
  });
});

CSS

ul { list-style:none; }
li {margin-bottom:20px; }

.check-container {
    position: relative;
    display:block;
    width:300px;
    height:200px;
    background: #e8e8e8;
}

.checkhidden { display: none; }

Hope that helps!

Edit

In order to check & uncheck the first item in the container just add the following two functions to your javascript:

$(".check-container").click(function () {
    var el = $(this).find("input:first");
    el.prop("checked", !el.prop("checked")).change();
});

$("input, label").click(function (e) {
    e.stopPropagation();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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