简体   繁体   中英

Jquery show div on checkbox

Hello i want to display a div when a checkbox is checked. The thing is i have multiple selects and i want to display the form until none is selected. My code is not working exactly as it should because when i deselect a checkbox my div dissapears and it should dissapear only if none is selected.

Here is my js

$('.checkbox').click(function() {
    if( $(this).is(':checked')) {
        $("#formular").show();
    } else {
        $("#formular").hide();
    }
}); 

also jsfiddle http://jsfiddle.net/bYuak/

Try

var $checks = $('.checkbox').click(function () {
    $("#formular").toggle($checks.filter(':checked').length>0);
});

Demo: Fiddle

Your code is called any time a click event is generated for any of your checkboxes, this happens because of this line of code:

$('.checkbox').click()

In side the event handler, you say :

if( $(this).is(':checked')) {
    $("#formular").show();
}

Which shows the div, and the else statement hides the div, if that element is unchecked. Therefore your code is working as expected. Your implementation however is very different to what you want it to do.

You need to check the state of all the checkboxes, using a loop and then show/hide the #formular div, if they are ALL unchecked.

This is how I do it:

function checkCount() {
    // Store count of how many selected
    var boxCount = 0,
        el = $("#formular");

    // Go through each checkbox
    $(".checkbox").each(function (index) {
        //Increase count if checked
        if ($(this).is(':checked')) {
            boxCount++;
        }
    });

    if (boxCount > 0) {
        el.show();
    }
    else {
        el.hide();
    }
}

$('.checkbox').on('change', function () {
    checkCount();
});

Its simple just target all checkboxes when you check.

$('.checkbox').click(function() {
    if(  $('.checkbox').is(':checked')) {
        $("#formular").show();
    } else {
        $("#formular").hide();
    }
}); 

See Fiddle: http://jsfiddle.net/bYuak/2/

try this

$('.checkbox').click(function() {
    if($(".checkbox:checked").length){
        $("#formular").show();
    }
    else{
        $("#formular").hide();
    }
}); 

Fiddle

or

$('.checkbox').click(function() { 
    $("#formular").toggle($(".checkbox:checked").length>0);
}); 

Fiddle

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