Is there a way to preserve html checkbox state after reload in Django?

Viewed 179

Sample code is below. I would like to keep the checkbox checked after page reload once submit button has been pressed

<td><input type="checkbox" value="{{ item }}" name="selectedcheckbox"/></td>
1 Answers

You can use the localStorage global object for that, for instance:

<input type="checkbox" id="checkbox1">checkbox</input>
<button type="button" onClick="save()">save</button>
function save() {   
    var checkbox = document.getElementById("checkbox1");
    localStorage.setItem("checkbox1", checkbox.checked);    
}

//for loading
let checked;
try {
  checked = JSON.parse(localStorage.getItem("checkbox1"));
} catch(e) {
  checked = false; // default value on error
  if (typeof e === 'object' && e.message) {
    console.error(e.message)
  }
}
document.getElementById("checkbox1").checked = checked;

The localStorage is saved in the user's browser, which does not persist with the same value for the entirety of browsers that the end user might be logged into

Related