Search code examples
javascriptjqueryhtmlcheckboxpageload

I need the javascript checkboxes.click(function()) to start when the page first loads


I am using the following js code to disable the form submit button until at least one checkbox selection is checked.

var checkboxes = $("input[type='checkbox']"),
    submitButt = $("input[type='submit']");

checkboxes.click(function() {
    submitButt.attr("disabled", !checkboxes.is(":checked"));
});

The problem is the code doesn't work when the page first loads. When the user first comes to the page, he is able to click submit but if he checks something and then unchecks everything the submit is then disabled.

It looks like I need the code to start when the page first loads. Any suggestions?


Solution

  • Add submitButt.attr("disabled", !checkboxes.is(":checked")); to disable the the submit button at first. Also, better wrap it in either domready or onload to ensure jQuery can access the fully rendered DOM.

    $(function() {
      var checkboxes = $("input[type='checkbox']"),
              submitButt = $("input[type='submit']");
    
      checkboxes.click(function() {
          submitButt.attr("disabled", !checkboxes.is(":checked"));
      });
      
      // Add this line to set init status of the submit.
      // submitButt.attr("disabled", true)); is ok as you don't have any checked checkbox when page loaded.
      submitButt.attr("disabled", !checkboxes.is(":checked"));
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <input type="checkbox" id="c1"/ >c1
    <input type="checkbox" id="c2"/ >c2
    <input type="checkbox" id="c3"/ >c3
    <input type="submit" value="click" />