473,804 Members | 3,312 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Javascript cookie Problem

toxicpaint
58 New Member
Hi there,

I've built a form for peolpe to submit a vote and I thought the best way to restrict people voting twice would be to create a cookie called "voted" and set the value to 1 when they vote.

When the page loads I want it to check for the cookie to see if that person has voted or not.

The script is creating a cookie called "vote" and setting it to 1.

I've attempted to write an if statement that checks this, but I can't get it to work.. What have I done wrong?

Thanks a lot!

Tom

Expand|Select|Wrap|Line Numbers
  1. <script language="javascript" src="cookies.js">
  2.  
  3.             function checkForVote(){
  4.             if (getCookie("voted") == "1"){
  5.             voteform.submitvote.disabled = true;
  6.             }
  7.             }
  8.             checkForVote();
  9.             </script>
  10. <form name="voteform" action="http://www.liv.ac.uk/cgi-bin/mailcomments.cgi" method="post">
  11. <input name="mailto" type="hidden" value="tcowling@liv.ac.uk">
  12. <input name="subject" type="hidden" value="Someone's Voted">
  13. <input name="required" type="hidden" value="email">
  14. <input name="email" type="hidden" value="someone@acomputer.com">
  15.               <div align="center">
  16.                 <select name="select">
  17.                   <option>Candidate 1</option>
  18.                   <option>Candidate 2</option>
  19.                 </select>
  20.                 <br />
  21.                 <br />
  22.                 <input type="button" value="Submit Vote" onclick='setCookie("voted", "1")' name="submitvote" />
  23.               </div>
  24.             </form>
  25.  
Nov 22 '06 #1
4 1989
kbiesbrock
1 New Member
I don't know for sure, but try this:
function checkForVote(){
if (getCookie("vot ed") == "1"){
document.votefo rm.submitvote.d isabled = true;
}
}
notice the "document." If that doesn't work put an alert("hi"); instead of document.votefo rm...... to see if it ever checks the cookie properly. If neither of those are the issue, physically check to see if the cookie is being created (probably your temp. internet files folder).

you could also try (heaven forbid any of the above don't work):
function checkForVote(){
test = getCookie("vote d");
alert(test);
}

Cheers! And good luck!
-Kevin
Nov 22 '06 #2
toxicpaint
58 New Member
Thanks for your help Kevin.

None of the above work.

The cookie is definetly being created because I'm using firefox and I've got the web developer toolbar that lets you see what cookies are being created on a page.

Am I calling the function right? Like.. As the page loads should it get to

checkForVote();

and then execute the if statement?

Cheers,

Tom
Nov 22 '06 #3
iam_clint
1,208 Recognized Expert Top Contributor
http://www.w3schools.com/js/js_cookies.asp
Nov 22 '06 #4
snowdonkey
37 New Member
In your code I don't think you're calling the function checkForVote() once the page loads, so it's never actually run.

I created an example that I think resembles what you're trying to do. Once the person votes, the Vote Button is disabled. I got the code for setCookie() and getCookie() functions from Peter Paul-Koch at http://www.quirksmode. org/js/cookies.html.

Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <head>
  3. <title>Vote Button</title>
  4. <script type="text/javascript">
  5. function checkForVote()
  6. {
  7.     // If there is a cookie...
  8.     if(document.cookie != "")
  9.     {
  10.         if(getCookie("voted") == 1)
  11.         {
  12.             // Disable the button again if user already voted. 
  13.             disableButton();
  14.         }
  15.     }
  16. }
  17.  
  18. function disableButton()
  19. {
  20.     var submitvote = document.getElementById("submitvote");
  21.     submitvote.disabled = true;
  22.     submitvote.value = "You Already Voted.";
  23. }
  24.  
  25. function setCookie(name, value, days)
  26. {
  27.     if(days) 
  28.     {
  29.         var date = new Date();
  30.         date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  31.         var expires = "; expires = " + date.toGMTString();
  32.     }
  33.  
  34.     else 
  35.     {
  36.         var expires = "";
  37.     }
  38.  
  39.     document.cookie = name + "=" + value + expires + "; path=/";
  40.  
  41.     // Disable the button as soon as the user clicks it.
  42.     disableButton();
  43. }
  44.  
  45. function getCookie(name) 
  46. {
  47.     var nameEQ = name + "=";
  48.     var ca = document.cookie.split(';');
  49.  
  50.     for(var i=0; i < ca.length; i++) 
  51.     {
  52.         var c = ca[i];
  53.  
  54.         while (c.charAt(0)==' ') 
  55.         {
  56.             c = c.substring(1,c.length);
  57.         }
  58.  
  59.         if (c.indexOf(nameEQ) == 0) 
  60.         {
  61.             return c.substring(nameEQ.length,c.length);
  62.         }
  63.     }
  64.  
  65.     return null;
  66. }
  67.  
  68. </script>
  69. </head>
  70.  
  71. <body>
  72. <form name="voteform" id="voteform" action="" method="post">
  73. <input type="button" name="submitvote" id="submitvote" onclick="setCookie('voted', 1, 365);" value="Submit Vote"/>
  74. </form>
  75. </body>
  76. <script type="text/javascript">
  77. // Run checkForVote() at end of document so that form and contents can be referenced
  78. window.onload = checkForVote();
  79. </script>
  80. </html>
  81.  
You can just copy & paste entire code to see it work. Hope it helps!
Nov 22 '06 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

0
7074
by: Gowhera Hussain | last post by:
Use This for Learning Only .... Do Not Try To Act Smart HACKING WITH JAVASCRIPT Dr_aMado Sun, 11 Apr 2004 16:40:13 UTC This tutorial is an overview of how javascript can be used to bypass simple/advanced html forms and how it can be used to override cookie/session
2
5590
by: Michael | last post by:
I am reading and setting a cookie using JavaScript in the BODY onload and onunload events respectively. This works fine. However when I use ASP to set the cookie under some condition where I want to override the last value set in the onunload event, it has no effect. The next onload still has the old value. Any ideas? The following code simulates the problem I experience. --------------------------------------------------
3
5979
by: M Wells | last post by:
Hi All, Just wondering how you go about changing the value of a session cookie via javascript? I have a PHP page that sets a session cookie when it first loads. I'd like to be able to change the value of that session cookie in response to a button click in a form, without resubmitting the page. For some reason, the following doesn't seem to work:
13
4296
by: Craig | last post by:
Hey all, Here's the situation: - two websites, one on domain1 and the other on domain2 - domain1 opens a new window which is a javascript app from domain2 - domain1 needs to communicate with the javascript app on domain2 The problem occurs in that last step. Browsers don't allow script access across domains for security reasons, rightly so. Nonetheless, I still
7
2250
by: Bert | last post by:
I have been reading the post and the FAQ and have been unable to find anything that will help with my problem. First let me say that I am not a web developer, designer and no next to nothing about javascript. I am just rebuilding my site and need help. We run a bamboo nursery and the site has listings of over 100 varieties we sell. The site uses regular pages and framesets for the discriptions of the bamboo. The framesets have a top...
7
2119
by: Steph | last post by:
Bonjour, Je souhaite lancer une redirection vers un fichier php via SRC= dans une condition if (voir ci-dessous en bas du script) mais la redirection ne fonctionne pas. Par contre la condition est bien validée car le cookie (crée précédemment) est bien effacé par SetCookie. Pourriez-vous me dire ce qui ne va pas ? Merci d'avance Steph
1
1543
by: Joe | last post by:
Hi folks, Been looking at this for the day so any ideas would be appreciated. Here's the scenario, bear with me - it looks more complicated than it is :) I have a page templating system that inherits from the page class and adds a mixture of usercontrols and literals when requested. One of the usercontrols is a menu that expands on being clicked using DHTML. What I'm trying to do is to persist the expanded menu to other pages or
3
11128
by: Wysiwyg | last post by:
After a server created cookie is processed on the client I want it removed, cleared, or expired in the javascript block but have been unable to do this. If I set a cookie value in the server code behind and don't use a domain then I can not change or remove that cookie's value on the client. If I subsequently create the cookie again in the codebehind then I actually end up with TWO cookies with the same name in the response. The cookie...
0
9705
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9575
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10564
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
7609
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6846
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5513
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5645
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3806
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2981
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.