简体   繁体   中英

jQuery. Check onload if checkbox is checked and add css to div

MY PROBLEM

jQuery(document).ready(function () {

if ($('input.pokazkontakt').prop(':checked')) {
    $(this).parent().nextAll('.pkbox:first').css('display', 'block');
} else {
    $(this).parent().nextAll('.pkbox:first').css('display', 'none');
}

$('input.pokazkontakt').click(function () {
    $(this).parent().nextAll('.pkbox:first').toggle('fast');
});
});

Demo

2nd part of JS is working (toogle), but i want to check first if checkbox is checked and hide the div or show. Where is a problem?

You can use .is()

if($('input.pokazkontakt').is(':checked'))

instead of if($('input.pokazkontakt').prop(':checked'))

Demo

Try this:

jQuery(document).ready(function () {

    $('input.pokazkontakt').each(function(){
        if ($(this).is(':checked')) {
            $(this).parent().nextAll('.pkbox:first').css('display', 'none');
        } else {
            $(this).parent().nextAll('.pkbox:first').css('display', 'block');    
        }
    });

    $('input.pokazkontakt').click(function () {
        $(this).parent().nextAll('.pkbox:first').toggle('fast');
    });
});
  • Use your logic reversely when you set display:none and display:block .
  • Use .is to check for checked state.
  • Use .each to iterate all your checkboxes

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