简体   繁体   中英

Check if checkbox is ALREADY checked on load using jQuery

I am currently using

 $("#some-box").click(function(){
     $("#main-box").toggle();
  });

Which works well, except for when the checkbox is part of a page that saves the checkboxes status. If a checkbox is saved as ticked, the main-box (which is revealed when the checkbox is clicked) is hidden on reload, and is only visible if the checkbox is clicked, which in now would mean "unticked" checkbox (as expected with the toggle).

How can I check on page load if the checkbox is already ticked, in which case to trigger the toggle automatically?

this should work:

if ($("#some-box").is(':checked')){
    $("#main-box").show();
}

You can get the initial state with .attr("checked") or .prop("defaultChecked") . However, I think the following is a better way:

function update() {
    $("#main-box")[this.checked ? "hide" : "show"]();
    // as by @zerkms, this is a different way for writing it:
    // $("#main-box").toggle(this.checked);
}
update.call($("#some-box").click(update)[0]);

For most events it is easy to just trigger it once for initialisation, but that doesn't apply here - we don't want to click (and change) the checkbox automatically onload.

.toggle() accepts the state - so you could pass whether to show or hide an element on a particular call:

$("#some-box").change(function(){
     $("#main-box").toggle($(this).is(':checked'));
  });

$('#some-box').trigger('change');

PS: as you can see I'm proposing to use change event instead of click

Online demo: http://jsfiddle.net/R4Bjw/

Use is(':checked') to test and show the box if the checkbox is checked:

if ($('#some-box').is(':checked')) {
    $('#main-box').show();
}

And then use your click handler as-is.

(function($) {
    var $somebox = $('#some-box'),
        $mainbox = $('#main-box');

    var toggleMain = function() {
        $mainbox.slideToggle();
    };

    if($somebox.is(':checked')) {
        toggleMain();
    }

    $somebox.on('click', toggleMain);
})(window.jQuery);

Here is a fiddle: http://jsfiddle.net/FX7Du/4/

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