-1

Hi i want to make a function when user submits a form, that button should remain disabled after refreshing the page. I have tried this method but it only disable for the page when i refresh it can be accessible.

<script>
    $('.reverse-form').one('submit', function() {
    $(this).find('input[type="submit"]').attr('disabled', 'disabled');
    });
</script>
  • 2
    You need to store the button state [in localstorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) which you can then access when the page refreshes. – Andy Sep 25 '22 at 10:22
  • https://stackoverflow.com/questions/16206322/how-to-get-js-variable-to-retain-value-after-page-refresh, https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads, https://stackoverflow.com/questions/11740669/saving-variable-value-and-retrieve-it-after-page-refresh, ... – Don't Panic Sep 26 '22 at 09:30

1 Answers1

1

You can use the localStorage that is able to store a key-value couple. If a key value isn't present in the localStorage null is returned that has false boolean value in javascript otherwise whatever string (except empty string "") has true boolean value.

Furthermore I used prop instead of attr because disabled is a boolean attribute (like checked selected) and in this case you have to use prop (otherwise with attr() you set or get the defaultChecked property namely the initial value of the disabled attribute, and in this case is the same but in general it isn't so)

<!DOCTYPE html>
<html lang="en">
  <head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script
  src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"
  integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA=="
  crossorigin="anonymous"
></script>
  </head>
  <body>
<form class="reverse-form">
  <input type="submit" />
</form>

<script>
  if (localStorage.submitDisabilitato) {
    $('form.reverse-form input[type="submit"]').prop("disabled", true);
  } else {
    $(".reverse-form").one("submit", function (e) {
      e.preventDefault();
      localStorage.submitDisabilitato = "submitDisabilitato";
      $(this).find('input[type="submit"]').prop("disabled", true);
    });
  }
</script>
  </body>
Nick
  • 1,439
  • 2
  • 15
  • 28