简体   繁体   中英

Inside an id div find all the checkbox and check and hide other unchecked

i am trying to learn and create a jquery which $("#answer") and find all the checkbox inside and check. As an example if checkbox inside #a1 is checked other div (a2,a3,a4) is hidden or other message come out. if i uncheck the #a1 all the div will come out again. Please enlighten me on the code.

  <div id="answer">
    <div id="a1">A.<input type="checkbox" name="a1" onclick="cbox()" ></input></div>
    <div id="a2">B. <input type="checkbox" name="a2"onclick="cbox()"></input></div>
    <div id="a3">C. <input type="checkbox" name="a3"onclick="cbox()"></input></div>
    <div id="a4">D. <input type="checkbox" name="a4"onclick="cbox()"></input></div>
                        </div>


function cbox() {
  if (this checkbox is checked)  { 
    target other div inside (#answer) and add .hide()
  }
}

2)Is there anyway to add a trigger where i don't need to use onlick="cbox" ?

tq

It's better to use .click() instead of inline javascript onclick .

However, you should use .change() event for input elements instead of click:

$('input[type="checkbox"]').change(function() {
    $(this).parent().siblings('div').toggle(!this.checked); 
});

Fiddle Demo

Use .change() event instead of .click() . Try this:

$('input[type="checkbox"]').change(function() {
    $(this).parent('div').siblings('div').toggle(!this.checked); 
});

DEMO

Try this:

$("#answer input").change(function () {
    if ($(this).is(":checked")) {
        $("#answer input").not(this).each(function () {
            $(this).parent().css("display", "none");
        })
    } else {
        $("#answer input").not(this).each(function () {
            $(this).parent().css("display", "block");
        })
    }
});

DEMO

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