?
Solved

I need to create cookies for my form

Posted on 2009-04-20
5
Medium Priority
?
720 Views
Last Modified: 2012-05-06
I need to modify my prototype form page so that when the JavaScript function has verified that all of the required fields have been filled, a cookie is added to the user's computer. If the same user attempts to fill out the form a second time, the user will be directed to a separate HTML page advising them that they have already submitted the form.

<script type'text/javascript'>

function formValidator(){
      //Make quick references to our fields
      var firstname = document.getElementById("firstname");
      var lastname = document.getElementById("lastname");
      var addr = document.getElementById("address");
      var city = document.getElementById("city");
      var zip = document.getElementById("zip");

      //Check each input in the order that is appears in the form!
      if(isAlphabet(firstname, "Please enter only letters for your First name")){
            if(isAlphabet(lastname, "Please enter only letters for your Last name")){
                  if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){
                        if(isAlphabet(city, "Please enter only letters for your City")){
                              if(isNumeric(zip, "Please enter a valid zip code")){
                                    return true;
                              }
                        }
                  }
            }
      }

return false;

}

function notEmpty(elem, helperMsg){
      if(elem.value.length == 0){
      alert(helperMsg);
      elem.focus(); // set the focus to this input
      return false;

      }

      return true;
}

function isNumeric(elem, helperMsg){
      var numericExpression = /^[0-9]+$/;
      if(elem.value.match(numericExpression)){
            return true;
      }else{
            alert(helperMsg);
            elem.focus();
            return false;
      }
}

function isAlphabet(elem, helperMsg){
      var alphaExp = /^[a-zA-Z]+$/;
      if(elem.value.match(alphaExp)){
            return true;
      }else{
            alert(helperMsg);
            elem.focus();
            return false;
      }
}

function isAlphanumeric(elem, helperMsg){
      var alphaExp = /^[0-9a-zA-Z]+$/;
      if(elem.value.match(alphaExp)){
            return true;
      }else{
            alert(helperMsg);
            elem.focus();
            return false;
      }
}
</script>


<form action="<C:\Documents and Settings\Gene\My Documents\WEB406\Individual\Week 2\Week2.1.html/>" method="post"  onsubmit="return formValidator(0)">
FirstName: <input type="text" id="firstname"/><br/>
LastName: <input type="text" id="lastname"/><br/>
Address: <input type="text" id="address"/><br/>
City: <input type="text" id="city"/><br/>
Zip: <input type="text" id="zip"/><br/>
<input type="Submit" Value="Submit"/>
</form>


0
Comment
Question by:Gday21
  • 2
4 Comments
 
LVL 29

Accepted Solution

by:
Pravin Asar earned 672 total points
ID: 24204509
Here is a complete cookie management code sample for you.

When you all fields are validated, you need to add call SetCookie function.



<html>
<head>
     <title>Cookies Tutorial by PravinAsar </title>
</head>
 
<body>
 
<script language="javascript">
// Delete cookie
 
function DeleteCookie(cookieName)
{
	if (!cookieName.length) {
	 	alert ('No cookie name specified'); 
		return;
	} 
    // Get All cookies;
     var  ck = document.cookie;
 
     // append "=" to cookiename
     
     var  cn = cookieName + "=";
     
     // Get cookie
     
     var pos = ck.indexOf (cn);
     // Cookie found 
 
     if (pos != -1) {
             // Set the start location for substring
             var start = pos + cn.length;
               // Get the end of cookie, start search from 'start' position.
               var end   = ck.indexOf (";", start);               
               // If end not found, set the end location equal to cookies length.
               if (end == -1) end = ck.length;
               //
               // Get Value of Cookies
               //
               var cookieValue= ck.substring (start, end);
               //alert ( "Cookie value : " + unescape (cookieValue));
               //create an instance of the Date object  
               var expDate = new Date(); 
               //set the date value to the past 
               expDate.setTime(expDate.getTime() - 1000 * 60 * 60 * 24 * 365); 
               //convert date to a GMT string 
               expDate = expDate.toGMTString(); 
               // recreate cookie string               
               var cookieString = cookieName + "=" + cookieValue + ";expires=" + expDate; 
               // update cookie
               document.cookie = cookieString; 
     }
     return;
}
 
// this function gets the cookie, if it exists
function GetCookieValue(cookiename)
{
    // get all cookies
     
     var  ck = document.cookie;
     // append "=" to cookiename
     var  cn = cookiename + "=";
     // search for cookie
     var pos = ck.indexOf (cn);
     // if found 
     if (pos != -1) {
             // set start location
             var start = pos + cn.length;
               // Get the end of cookie, start search from 'start' position.
               var end   = ck.indexOf (";", start);
               // If end not found, set the end location equal to cookies length.               
               if (end == -1) end = ck.length;
               //
               // Get Value of Cookies
               //
               var cookieValue= ck.substring (start, end);
               //
               // Write the current document.
               //
               //document.write  ( "<br>Cookie value : " + unescape (cookieValue));
				return (cookieValue);
     }
     return (null);
}
 
function GetCookies() {
    // Get cookies
     var  ck = document.cookie;
     var  ix=0;
     //
     // split the cookie string at ";"
     //
     var strs = ck.split (';');
     for (ix=0; ix <strs.length; ix++) {
          //document.write ("<br><br>Cookie " + ix + " " + unescape(strs[ix]));
          //split current strs[ix] at "="
          var ckvar= strs[ix].split('=');
          //
          // Write the current document.
          //
          //document.write ("<br>Cookie Name " + ckvar[0]);
          //
          // Get cookie value;
          //          
          var cv= GetCookieValue(ckvar[0]);
          document.write ("<br>Cookie Name " + ckvar[0]);
          document.write ("<br>Cookie Value" + cv);
     }
     return ;
}
 
function SetCookie(cookieName,cookieValue,nDays) {
	if (!cookieName.length)
	{
		alert ('No cookie name specified');
		return;
	} 
    // Initialize date variable
     var today = new Date();
     var expire = new Date();
     // Validate input nDays
     if (nDays==null || nDays < 1 ) nDays=1;
     //
     // Add time to expire variable, it is milliseconds *hour 
     // 1 day has 24 hours , 1 hour has 3600000 milliseconds;
     //
     expire.setTime(today.getTime() + 3600000*24*nDays);
      document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}
 
function GetAndDeleteCookies() {
    // Get cookies
     var  ck = document.cookie;
     var  ix=0;
     //
     // split the cookie string at ";"
     //
     var strs = ck.split (';');
     for (ix=0; ix < strs.length; ix++) {
          //document.write ("<br><br>Cookie " + ix + " " + unescape(strs[ix]));
          //split current strs[ix] at "="
          var ckvar= strs[ix].split('=');
          //
          // Write the current document.
          //
          document.write ("<br>Deleting Cookie Name " + ckvar[0]);
		  //
          // Delete Cookie
		  //
          DeleteCookie(ckvar[0]);
     }
     return ;
}
function GetCheckBoxValues(chkObj)
{
	var ix=0;
	var values="";
	for (ix=0; ix <chkObj.length;ix++) {
		if (chkObj[ix].checked) {
			values += chkObj[ix].value + ',';
		}
	}
	return (values);	
}
</script>
 
<form name="MyForm" action="cookie.htm" method="post">
COOKIE NAME:<input type="text" name="cookiename" value="MyChkBox">
<br>
COOKIE VALUE:
<b>Scripts for Web design and programming</b><br>
<input type="checkbox" name="cookievalue" value="1"  onclick="GetCheckBoxValues(document.MyForm.cookievalue);">ASP<br>
<input type="checkbox" name="cookievalue" value="2">PHP<br>
<input type="checkbox" name="cookievalue" value="3">JavaScript<br>
<input type="checkbox" name="cookievalue" value="4">HTML<br>
<input type="checkbox" name="cookievalue" value="5">MySQL<br>
 
<br>
<!--COOKIE VALUE:<input type="text" name="cookievalue" value="">-->
<!-- You can use select -->
<!--select  name="cookievalue">
	<option value="CA">California</option>
	<option value="FL">Florida</option>
	<option value="GA">Georgia</option>
	<option value="NY">New York</option>
	<option value="TX">Texas</option>
</select-->
<!-- You can use Check Box -->
<input type="button" value="Set Cookie" onClick="SetCookie(this.form.cookiename.value, GetCheckBoxValues(document.MyForm.cookievalue),1);">
<input type="button" value="Delete Cookie" onClick="DeleteCookie(this.form.cookiename.value);">
<br><input type="button" value="Inquire All Cookies" onClick="GetCookies();">
<br><input type="button" value="Delete All Cookies" onClick="GetAndDeleteCookies();">
</form>
<script language="javascript">
GetCookies();
</script>
</body>
</html>

Open in new window

0
 
LVL 3

Assisted Solution

by:dkellner
dkellner earned 1328 total points
ID: 36556416
Are you sure you're able to run javascripts on localhost?
It seems that you're using filesystem paths in your FORMs ACTION parameter.

Try using a webserver. Maybe your browser doesn't even tell you that something's wrong, just doesn't run your scripts.

I take a second look - this was just a first note as I scrolled down.
0
 
LVL 3

Assisted Solution

by:dkellner
dkellner earned 1328 total points
ID: 36556425
As for the cookie handling, here's a very short & straightforward kit:


 
var ckObj=document.cookie;
var ckT=new Date();
var ckY=365*24*60*60*1000;
var ckE=new Date(ckT.getTime()+ckY);

function getCookie(name) {
	var i=ckObj.indexOf(name+"=");if(i==-1) return null;
	i=ckObj.indexOf("=",i)+1;var e=ckObj.indexOf(";",i);if(e==-1) e=ckObj.length;
	return unescape(ckObj.substring(i,e));
}
function setCookie(name,value) {
	if(value==null)return;if(value=="")return;
	document.cookie=name+"="+escape(value)+";
	expires="+ckE.toGMTString();
	ckObj=document.cookie;
}
function setTmpCookie(name,value) {
	if(value==null)return;if(value=="")return;
	document.cookie=name+"="+escape(value);
	ckObj=document.cookie;
}

Open in new window

0
 
LVL 16

Expert Comment

by:CWS (haripriya)
ID: 37175626
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question