Home > Enterprise >  How to limit number of button clicks per day in Javascript?
How to limit number of button clicks per day in Javascript?

Time:01-22

I want to limit the number of clicks on a button per day to 5 clicks using cookies. So when a user clicks 5 times, the button will no longer be clickable. I managed to do that, but the problem is when I refresh the page, the button is clickable again. So how to apply cookies to remember the user clicks?

My code:

<input type="text"  id="prompt" placeholder="Type anything">
<button id="the-button" type="submit">Send</button>
<script
  src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
  crossorigin="anonymous">
</script>   
<script type="text/javascript">                                         
localStorage.setItem("limit_click",5);
localStorage.setItem("count",1);
$("#the-button").on("click",function(){
    var limit = localStorage.getItem("limit_click");
    let count = parseInt(localStorage.getItem("count"));    
    if(count>=limit){
        alert('Your free limit counts has expired, please try again tomorrow or consider extending your plan.');
    }
    else{
        localStorage.setItem("count",parseInt(count) 1);
    }
}); 
</script>

I blocked the button when clicked 5 times. But, when page is refreshed, the button is clickable again.

What I want to do: Block the button after 5 clicks, and then even when the page is refreshed, the button is still blocked.

CodePudding user response:

Your code fails to check the localStorage before setting it to 1. Every page load you do localStorage.setItem("count",1);. This resets the count to 1, so every page load the localStorage is refreshed. This doesn't make sense, so do:

if(!localStorage.getItem("count")){
    localStorage.setItem("count",1);
}
  • Related