Disable Button After Click for Each User

Viewed 164

I am working on a budgeting app using PHP HTML and a touch of JS.

I want to have an import button that can only be clicked one time by the user then it is disabled or hidden even if they refresh the page, But for a new user, it would still be available until they click it.

I have tried code like this but it is available to click again after each refresh.

<form action='/' method='POST' onsubmit='disableButton()'>
    <input name='txt' type='text' required />
    <button id='btn' type='submit'>Post</button>
</form>

<script>
    function disableButton() {
        var btn = document.getElementById('btn');
        btn.disabled = true;
        btn.innerText = 'Posting...'
    }
</script>

Is there any way to accomplish this?

1 Answers

For this, as some others have said, you are going to need an backend database, but, we can also implement this using localstorage and cookies. Here is how you could do it:

<form action='/' method='POST' onsubmit='refresh()'>
    <input name='txt' type='text' required />
    <button id="refresh" type='submit'>Post</button>
</form>
<script>
  const refreshBtn = document.getElementById("refresh");
  refreshBtn.addEventListener("click", refresh);
  disable();

  function disable() {
    if (localStorage.getItem("disableButton?")) {
      refreshBtn.setAttribute("disabled", ""); 
    }
  }
  
  function refresh() {
    localStorage.setItem("disableButton?", "yes");
  };
</script>

Code explanation: When you submit the form, it saves in local storage that the button is clicked. Then when the user comes back, it runs disable() which checks if the local storage value exists, and if it does, it disables the submit button.

If this doesn’t work please tell me.

(Also, if the user clears his history and cookies, then the user will be able to submit the form, so it’s better to use an database for this then doing this.)

Related