Reputation: 466
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?
Upvotes: 0
Views: 1327
Reputation: 68923
You can store the state in sessionStorage
or localStorage
and use that on page load to set the attribute:
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 tosessionStorage
, except that while data stored inlocalStorage
has no expiration time, data stored insessionStorage
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
.....
});
Upvotes: 7