简体   繁体   中英

hide div when no checkbox is checked

I am trying to show hidden text if at least one checkbox is checked and hide it if none are checked. I have a multiple checkboxes.The hidden text isn't showing when I check the checkooxes. Any help? Here is fiddle http://jsfiddle.net/HDGJ9/1/

<input type="checkbox" name="ch[]">
<input type="checkbox" name="ch[]">
<input type="checkbox" name="ch[]">
<input type="checkbox" name="ch[]">
<div class="txt" style="display:none">


if($('input[name="ch[]"]').is(':checked'))
$(".txt").show();  // checked
else
$(".txt").hide();  // unchecked

Enclose/wrap your code with event handler like

$('input[name="ch[]"]').on('change', function () {
 //your code

});

JSFiddle

You can just check the length of checked checkboxes...

var $checkboxes = $(':checkbox');
$checkboxes.on('change', function(){
  $('.txt').toggle( $checkboxes.filter(':checked').length > 0 );
});

Nothing is executing your javascript code. There are many ways to execute, and also many ways to achieve the result you want. You can assign it to a click or change event like so:

$("input[name='ch[]']").click(function() {
    if($('input[name="ch[]"]').is(':checked'))
        $(".txt").show();  // checked
    else
        $(".txt").hide();  // unchecked
});

Here is an updated fiddle that checks your function everytime you click.

In your code, the test for checked/unchecked boxes occurs only once, when the page loads. You should run this check every time the value of any of the checkboxes changes. Something like

function refresh() {
    if ($('input[name="ch[]"]').is(':checked')) {
        $(".txt").show(); // checked
    } else {
        $(".txt").hide(); // unchecked
    }
}

$('input:checkbox').change(refresh);

JSFiddle: http://jsfiddle.net/MHB8q/1/

You are selecting all four checkbox elements here, you need to only select one that is checked, and see if you get a result:

if($('input[name="ch[]"]').filter(':checked').length){
    $(".txt").show();  // checked
} else {
    $(".txt").hide();  // unchecked
}

Demo: http://jsfiddle.net/HDGJ9/10/

$('input[name="ch[]"]').on('change', function() {

  if ($(this).is(':checked')) {
    $('.txt').css('display', 'block');
  }

  else {
    var checked = false;
    $('input[name="ch[]"]').each(function(i, el) {
      if ($(el).is(':checked')) checked = true;
    });
    if (!checked) $('.txt').css('display', 'none');
  }

});

Version with the least amount of event handlers:

$(document).on("change", ":checkbox", function(){
var isAtLeastOneCheckboxChecked = $(':checkbox').filter(":checked").length > 0;
if (isAtLeastOneCheckboxChecked)
    $('.txt').show();
else
    $('.txt').hide();
});

Fiddle: http://jsfiddle.net/3d79N/

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