menu

Questions & Answers

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

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" class="form-control" 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.

Comments:
2023-01-22 00:10:08
Do you realise that I "the user" can clear cookies
2023-01-22 00:10:08
You might want to look at browser fingerprinting as a means of identifying unique visitors and using a db rather than a cookie which, as mentioned, can be cleared or otherwise modified
2023-01-22 00:10:08
Wrong approach. Use a server side storage like a database and count it there.
2023-01-22 00:10:08
I just want this as a workaround. I'm still learning since this is a school project.
2023-01-22 00:10:08
Well now you have learned that this is not really a solution to this problem, but you have been offered some edification by people suggesting other ways that would work
2023-01-22 00:10:08
I understand this is not a good approach but this is just for a school project. I'd be glad if I'd get help atm.
Answers(1) :

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);
}
Comments:
2023-01-22 00:10:08
This worked! My bad, thank you for explaining too.