dimanche 29 janvier 2023

Checkbox State Persistence before and after form submission

I am new to web developing. Apologies, if this is too simple but could not find the right way to fix this issue.

I have been asked to make a simple form with several checkboxes having a unique name and different values. No problem for that. The issue I am encountering is that I have also been asked that I need to have all the checkboxes checked by default before submission and only to keep the checkboxes that remain checked, checked after the form submission. My code below does not make them all checked by default but save the results after form submission. Even adding the statement checked on the input tag does not change much.

 <form onsubmit="return saveCheckboxValue();">
  <label for="checkbox1">Option 1</label>
  <input type="checkbox" id="checkbox1">
  <br>
  <label for="checkbox2">Option 2</label>
  <input type="checkbox" id="checkbox2">
  <br>
  <label for="checkbox3">Option 3</label>
  <input type="checkbox" id="checkbox3">
  <br>
  <input type="submit" value="Submit">
</form>
   <script>
function saveCheckboxValue() {
  // Get all checkbox elements
  var checkboxes = document.querySelectorAll("input[type='checkbox']");


  for (var i = 0; i < checkboxes.length; i++) {
    if (checkboxes[i].checked) {
      localStorage.setItem(checkboxes[i].id, true);
    } else {
      localStorage.removeItem(checkboxes[i].id);
    }
  }
  return true;
}

window.onload = function() {
  // Get all checkbox elements
  var checkboxes = document.querySelectorAll("input[type='checkbox']");


  for (var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].checked = JSON.parse(localStorage.getItem(checkboxes[i].id)) || false;
  }
};
</script>

I tried to change the value to true

> window.onload = function() {   // Get all checkbox elements   var
> checkboxes = document.querySelectorAll("input[type='checkbox']");
> 
>   for (var i = 0; i < checkboxes.length; i++) {
>     checkboxes[i].checked = JSON.parse(localStorage.getItem(checkboxes[i].id)) || true;   } };

But by doing this, the checkboxes will be checked by default which is good, but if I uncheck some and submit the form, even the unchecked ones will be checked after the form submission.




Aucun commentaire:

Enregistrer un commentaire