user1945912
user1945912

Reputation: 617

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?

Upvotes: 16

Views: 29433

Answers (5)

zerkms
zerkms

Reputation: 254944

.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/

Upvotes: 6

Paul
Paul

Reputation: 12440

(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/

Upvotes: 1

Bergi
Bergi

Reputation: 664620

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.

Upvotes: 5

carrabino
carrabino

Reputation: 1762

this should work:

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

Upvotes: 30

Ben Lee
Ben Lee

Reputation: 53319

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.

Upvotes: 1

Related Questions