简体   繁体   中英

How to enable/disable a button via checkbox and keep the button active or inactive after refreshing the page

I have a button and I want to do the following

  • Disable this button by clicking on the checkbox that refers to it
  • Keep it disabled even after refreshing the page
  • Do the same, but instead. The button is disabled and now I would like to enable it again by clicking on the checkbox that references it keeping it that way after refreshing the page

I found two references that do exactly what I need, but I don't know how to put the two solutions together. This and this

HTML code

<div id="billing">
    <input type="checkbox" id="billing-checkbox" checked>
    <input type="button" value="Hello Javascript!">
</div>

Javascript code

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('billing-checkbox').onchange = toggleBilling;
    }, false);

    function toggleBilling() {
    var billingItems = document.querySelectorAll('#billing input[type="button"]');

    for (var i = 0; i < billingItems.length; i++) {
        billingItems[i].disabled = !billingItems[i].disabled;
    }
    }

    $(function(){
        var test = localStorage.input === 'true'? true: false;
        $('input').prop('checked', test || false);
    });

    $('input').on('change', function() {
        localStorage.input = $(this).is(':checked');
        console.log($(this).is(':checked'));
    });

Thank you so much!

This will give a script error in the snippet, probably because it is a sandbox and doesn't allow for localStorage. But this is tested and works. See comments in the code for explanations. You can set the checkbox on or off and when you refresh the page, it will 'remember' it's state

 $(document).ready(function() { // first thing is to set the checkbox based on the localStorage key that we may have set in the past $('#billing-checkbox').prop('checked', localStorage.getItem('buttonDisabled') !== "disabled"); // then we run our toggle billing toggleBilling() // we set up our change handler. $('#billing-checkbox').on('change', toggleBilling); }); function toggleBilling(e) { // we set the disabled based on the check button status $('#billing input[type="button"]').attr('disabled', !$('#billing-checkbox').prop('checked')) // we set the localStorage based on the button disabled localStorage.setItem('buttonDisabled', $('#billing input[type="button"]').attr('disabled')); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="billing"> <input type="checkbox" id="billing-checkbox" checked> <input type="button" value="Hello Javascript!"> </div>

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