Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey,

I want to limit the amount of clicks that can be pressed on a button using cookies. I know the cookies can just be cleared but in this case that will be fine.

So for example:

When I press BUTTON one time, nothing will happen, I press again nothing will happen, however when I press it the third time it will set a cookie and not allow the button to be pressed again until the cookie expires (5 min maybe?).

I have a functioning example below however I need to implement so it uses cookies.

Thank you in advance.

What I have tried:

<script type="text/javascript">
var ClickCount = 0;
function countClicks() {
	var clickLimit = 3; //Max number of clicks
	if(ClickCount>=clickLimit) {
		alert("You can only click this button "+clickLimit+" times.");
		return false;
	}
	else
	{
		ClickCount++;
		return true;
	}
}
</script>

<input type="button" value="Click me only three times!" name="clickThree" onclick="return countClicks();" />
Posted
Updated 30-Jun-18 18:50pm
v4

1 solution

Okay, that's quite simple with the code you've tried. You just need to set the flag in the cookie, and set a timeout to check if the cookie has expired or not.

You can find the methods that allows you to get and set cookies from here -
JavaScript Cookies[^]

JavaScript setTimeout() -
JavaScript Timing Events[^]

function countClicks() {
	var clickLimit = 3; //Max number of clicks
	if(ClickCount>=clickLimit) {
       // SET YOUR COOKIE HERE AND DISABLED THE BUTTON
		alert("You can only click this button "+clickLimit+" times.");
		return false;
	}
	else
	{
		ClickCount++;
		return true;
	}
}

// CHECK COOKIE
setTimeout(function(){
// CHECK IF THE COOKIE IS EXISTS AND ENABLE THE BUTTON
}, 1000);


I hope you get the idea.


KR
 
Share this answer
 
Comments
Member 13891475 1-Jul-18 15:09pm    
I do get the idea, but can't get it to work..

Can you make a example on jsfiddle?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900