Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 371
user1945912 Avatar asked May 08 '13 23:05

user1945912


People also ask

How do you checkbox is checked or not in jQuery on page load?

We can check the status of a checkbox by using the :checked jQuery selector together with the jQuery function is . For example: $('#el').is(':checked') .

How do you check if a checkbox is checked?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

How do you check checkbox is checked or not on page load?

JS code: // Checkbox checked and input disbaled when page loads $('#checkbox'). prop('checked', true); if ($('#checkbox').is(':checked') == true) { $('#textInput').


2 Answers

this should work:

if ($("#some-box").is(':checked')){
    $("#main-box").show();
}
like image 83
carrabino Avatar answered Sep 20 '22 11:09

carrabino


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

like image 20
zerkms Avatar answered Sep 23 '22 11:09

zerkms