M. Bran
M. Bran

Reputation: 21

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

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!

Upvotes: 0

Views: 220

Answers (1)

Kinglish
Kinglish

Reputation: 23664

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>

Upvotes: 1

Related Questions