Home > Enterprise >  How to disable html button for 24hrs after being clicked
How to disable html button for 24hrs after being clicked

Time:09-29

I'm trying to create a button that disable after being clicked and will be enable after 24hrs. The button should work for each users. How can I fix that?

    <p>
        <input type='submit' value='Submit' id='btClickMe' 
            onclick='save(); this.disabled = true;' />
    </p>
    <p id="msg"></p>
<script>
    function save() {
        var msg = document.getElementById('msg');
        msg.innerHTML = 'Data submitted and the button disabled in 24hrs  &#9786;';
    }
</script>

CodePudding user response:

store clicked identifier to cookie which expired after 24 hours from first button clicked (using document.cookie)

<input
  type="submit"
  value="Submit"
  id="btClickMe"
/>
<div id="msg">Message Here</div>
const btn = document.getElementById("btClickMe");
let get = getCookie("clicked"); // check cookie after page loaded
if (get) {
  btn.disabled = true; // disable the button after page loaded
}

btn.addEventListener("click", function (_event) {
  get = getCookie("clicked"); // check cookie exist
  if (!get) setCookie("clicked", "true", 1); // set cookie after clicked
  btn.disabled = true; // disable the button after button clicked
  var msg = document.getElementById("msg");
  msg.innerHTML = "Data submitted and the button disabled in 24hrs  &#9786;";
});

function setCookie(name, value, days) {
  var expires = "";
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()   days * 24 * 60 * 60 * 1000);
    expires = "; expires="   date.toUTCString();
  }
  document.cookie = name   "="   (value || "")   expires   "; path=/";
}
function getCookie(name) {
  var nameEQ = name   "=";
  var ca = document.cookie.split(";");
  for (var i = 0; i < ca.length; i  ) {
    var c = ca[i];
    while (c.charAt(0) == " ") c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}

See Demo

CodePudding user response:

So you store last click time on localStorage and restore it when loading the page. I calculate the difference using seconds. Just a note: localStorage doesn't work on this sandbox. But it should work for you.

function save() {
  var now = Math.round(new Date().getTime() / 1000);
  localStorage.setItem("last_save", now)
  // ...
}

window.addEventListener('load', function() {
  var now = Math.round(new Date().getTime() / 1000);
  var then = localStorage.getItem("last_save") || 0;
  var diff_seconds = now - then
  if (diff_seconds > 24 * 60 * 60) {
    document.querySelector("button").disabled = false;
  }
})
<button disabled>save</button>

  • Related