Skip to content
Advertisement

How to keep the Input field inside the session storage and disabled upon refresh?

I want to disable the input field after the user clicks the “disable” button, and automatically change the “disable” button to “enable”, disabling the input fields at the same time. But, if we refresh or press Ctrl+F5, the disabled fields becomes enabled and editable. Below is the code I have, what should I do to keep it disabled even upon refresh and changing the button? Thank you.

html

<input  id="firstname"></input>
<input  id="lastname"></input>
<input  id="email"></input>

<button type="button" class="dropdown-item" id="status">Disable</button>

script

const disableInputs = function() {
    sessionStorage.disableInputs = 'true';
    document.getElementById('firstname').disabled = true;
    document.getElementById('lastname').disabled = true;
    document.getElementById('email').disabled = true;

    var elem = document.getElementById("status");
    
    if (elem.value=="Disable") elem.value = "Enable";
    else elem.value = "Disable";
  };
  if (sessionStorage.disableInputs === 'true') disableInputs();
  document.getElementById('status').onclick = disableInputs;

The button is displaying enable from disable after adding onlick change() but it doesn’t save at state upon refresh, is this correct?

<button type="button" onclick="change();" id="status">Disable</button>
function change()
{
    var elem = document.getElementById("status");
    
    if (elem.value=="Disable") elem.value = "Enable";
    else elem.value = "Disable";
}

Advertisement

Answer

Firstly, you need first get state of disabled state from sessionStorage by using getItem and Save data using setItem

disabled = !disabled; used to toggle a variable state, So if it’s true change it to false and vice versa.

const status = document.getElementById('status');
const firstname = document.getElementById('firstname');
const lastname = document.getElementById('lastname');
const email = document.getElementById('email');
let disabled = JSON.parse(sessionStorage.getItem("disableInputs") ?? 'false');
firstname.disabled = lastname.disabled = email.disabled = disabled;
status.innerText = disabled ? 'Disable' : 'Enable';

function toggle() {
  disabled = !disabled;
  firstname.disabled = lastname.disabled = email.disabled = disabled;
  status.innerText = disabled ? 'Disable' : 'Enable';
  sessionStorage.setItem('disableInputs', disabled);
};
<input id="firstname" />
<input id="lastname" />
<input id="email" />
<button type="button" onclick="toggle();" id="status">Disable</button>

Note: <input> is an empty tag, in that it’s not designed to have any content or a closing tag. For compliance, you can signify the end of the tag by using it like this: <input id="firstname" />

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement