How do you maintain the state of a checkbox-toggled div after page reload?

后端 未结 1 1034
轻奢々
轻奢々 2021-01-16 08:56

I have a div that appears when a checkbox is checked, and hides when unchecked. If the form has errors, the page reloads and the div appears hidden even if the checkbox was

相关标签:
1条回答
  • 2021-01-16 09:11

    Option 1

    Ensure div is shown based on check box when the page loads:

    $(document).ready(function() {
         // Modified for readability - inline if is fine.
         if($("#check-hasMaintenance").is(":checked"))
             $('#maintenance-window').show("fast")
         else
             $('#maintenance-window').hide("fast");
    });
    

    Simplified hide/show code:

    $("#check-hasMaintenance").click(function() {
        $('#maintenance-window').toggle('fast');
    });
    

    Option 2

    A short-hand version like this should work as well:

    $(document).ready(function() {
        $('#maintenance-window').toggle($("#check-hasMaintenance").is(":checked"));
    });
    
    $("#check-hasMaintenance").click(function() {
        $('#maintenance-window').toggle('fast');
    });
    
    0 讨论(0)
提交回复
热议问题