简体   繁体   中英

How to store state of disable button(s) even after refreshing a page?

I have two buttons on my page. If a user clicks one, the other gets disabled and vice versa. Suppose if, 'Button1' was enabled. This means that 'Button2' gets disabled. And now, when I click on 'Button 2'.... 'Button1' gets disabled . However, when I refresh the page, 'Button1' gets enabled and 'Button2' gets disabled again . How can I store the state of the last disabled button and view it after refreshing the page?

This is what I tried so far:

template.html:

<button type="button" id ='button1'> Button 1 </button> 
<br> <br>
<button type="button" id ='button2' disabled /> Button 2 </button>

template.js (using Jquery):

    $('#button1').click(function () {
        $("#button1").attr("disabled", true);
        $("#button2").attr("disabled", false);

    $('#button2').click(function () {
        $("#button2").attr("disabled", true);
        $("#button1").attr("disabled", false);

How can I store the last state of the disabled button after refreshing the page?

You can store the state in sessionStorage or localStorage and use that on page load to set the attribute:

localStorage

The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage , except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed.

var disbledBtn = localStorage.getItem('disabled'); // get the id from localStorage
$(disbledBtn).attr("disabled", true); // set the attribute by the id

$('#button1').click(function () {
  $("#button1").attr("disabled", true);
  $("#button2").attr("disabled", false);
  localStorage.setItem('disabled', '#button1'); // store the id in localStorage
  ......
});
$('#button2').click(function () {
  $("#button2").attr("disabled", true);
  $("#button1").attr("disabled", false);
  localStorage.setItem('disabled', '#button2'); // store the id in localStorage
  .....
});

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