JavaScript - Javascript Cookies, Saving Form Data
Hello,
Im pretty new at JavaScript still, and I am trying to add cookies to a page of my website, so that what is entered into form fields, is retained for future visits. Below is my code, and I am scratching my head as to why it is not working for me! I have viewed a few different cookie tutorials, and so far trying to shape them around what I am seeking, is leading me to my broken code. Javascript: Code: var today = new Date(); var expiry = new Date(today.getTime() + 100 * 24 * 3600 * 1000); function setCookie(name, value) { document.cookie=name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString(); } function storeValues(form) { setCookie("name", contact.name.value); setCookie("email", contact.email.value); setCookie("phone", contact.phone.value); return true; } if(name = getCookie("name")) document.contact.name.value = name; if(email = getCookie("email")) document.contact.email.value = email; if(phone =getCookie("phone")) document.contact.phone.value = phone; HTML for the Form Code: <form action="mailto:ksim@dbk.com" method="POST" name="contact" onsubmit="return validateForm();" > <ul> <li> <strong>Name<font color="#5fb81e">*</font></strong> <div><input type="text" size="25" name="name" /></div> </li> <li> <strong>E-mail Address<font color="#5fb81e">*</font></strong> <div><input type="text" size="25" name="email" /></div> </li> <li> <strong>Phone Number<font color="#5fb81e">*</font></strong> <div><input type="text" size="25" name="phone" /></div> </li> <li> <strong>Prefered Type of Contact?<font color="#5fb81e">*</font></strong> <div><input type="radio" name="contact" value="email" id="contactem" /> E-mail<br /> <input type="radio" name="contact" value="phone" id="contactph" /> Phone</div> </li> <li> <strong>Reason For Contact?</strong> <div><input type="checkbox" name="reason" value="showinfo" />Show Information<br /> <input type="checkbox" name="reason" value="groupinfo" />Group Information<br /> <input type="checkbox" name="reason" value="collab" /> Collaboration<br /> <input type="checkbox" name="reason" value="misc" />Misc </div> </li> <li> <strong>What Are You Contacting About?<font color="#5fb81e">*</font></strong> <div><textarea name="message" rows="7" cols="28"></textarea></div> </li> <li> <strong></strong> <div><input type="button" value="Save" conclick="setCookie();"/><button type="reset">Reset</button><button type="submit">Submit</button> </div> </li> </ul> If anyone has some tips to point me in the right direction, and let me see the error of my ways (pun totally intended) I would appreciate it. Similar Tutorialshello people! i would like to ask if someone can help me code a couple of scripts for saving various data into cookies, and then post them to e-mail through a cgi script. to be more clear, i want to save some questionare's answers given through a series of html pages, to cookies. when (and if) the last question is answered, send all the answers to an e-mail address. thanks! I'm trying to get my form to save a user's data via cookies. I found a script at http://www.fijiwebdesign.com/blog/re...ubmission.html, and it only seems to work if you refresh the page, but not if you close out the browser and restart. Code: <form action="process-contact.php" id="contact" method="post"> Name: <input type="text" name="name"/> <br />Email: <input type="text" name="email"/> <br />Message: <textarea name="message"></textarea> <br /><input type="submit" value="Submit"/> </form> <script type="text/javascript"> window.onload = function() { rememberFormInputs('contact', 'input-'); } /** * Set a cookie * @param string cookie name * @param string cookie value * @param string cookie expiration counter in days * @param string cookie path * @param string cookie domain * @param bool secure? */ function setCookie(name, value, expires, path, domain, secure) { var today = new Date(); today.setTime(today.getTime()); if (expires) { expires = expires * 1000 * 60 * 60 * 24; } var expires_date = new Date(today.getTime() + (expires)); document.cookie = name+"="+escape(value) + ((expires) ? ";expires="+expires_date.toGMTString() : "") + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : ""); } /** * Get a cookie value * @param string cookie name */ function getCookie(name) { var start = document.cookie.indexOf(name + "="); var len = start + name.length + 1; if ((!start) && (name != document.cookie.substring(0, name.length))) { return null; } if (start == -1) return null; var end = document.cookie.indexOf(";", len); if (end == -1) end = document.cookie.length; return unescape(document.cookie.substring(len, end)); } /** * Remebers form inputs after you fill them in * @param string form id to remember fields * @param string a prefix to prepend to all cookie names. (prevent naming conflicts) */ function rememberFormInputs(form_id, prefix) { var form = document.getElementById(form_id); var els = document.getElementsByTagName('input'); for (var i = 0; i < els.length; i++) { var el = els.item(i); if (el.type == 'text') { el.onblur = function() { var name = this.name; var value = this.value; setCookie(prefix + name, value); }; var old_value = getCookie(prefix + el.name); if (old_value && old_value != '') { el.value = old_value; } } } } </script> The demo on the site I got this code from is a broken link. I would really appreciate any and all help to get this resolved. I know cookies are suppose to save even after closing out the browser. Hi guys, Been stuck for a few days with this scenario. Any help? The alert box appears on an error. But the submitting won't stop. The details are submitted and the form is processed. Any help is greatly appreciated... Code: <html> <head> <script type="text/javascript" src="email_helper/jscripts/tiny_mce/tiny_mce.js"></script> <script type="text/javascript"> tinyMCE.init({ // General options mode : "textareas", theme : "simple" }); </script> <script language="javascript"> function MM_openBrWindow(theURL,winName,features) { window.open(theURL,winName,features); } function err_check(){ var email = document.getElementById('to_email').value; if(email.length==0){ alert('Please Enter Email Address'); return false; } var AtPos = email.indexOf("@") var StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { alert("Please Enter Valid Email Address"); document.getElementById('email').focus(); return false; } email = document.getElementById('cc_email').value; if(email.length != 0){ var AtPos = email.indexOf("@") var StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { alert("Please Enter Valid Email Address"); document.getElementById('email').focus(); return false; } } var answer = confirm ("Send E-Mail?"); if (!answer){ return false; } } </script> <!-- /TinyMCE --> <style type="text/css"> body, table, td, th{ background-color:#CCCCCC; font-family: Arial; font-size:14px; } .que{ font-weight:bold; } </style> </head> <body> <form method="post" enctype="multipart/form-data"> <?php include 'library/database.php'; include 'library/opendb.php'; $query = mysql_query("SELECT email,contact,mobile FROM users WHERE user_id='$uid'") or die(mysql_error()); $row = mysql_fetch_row($query); $from_email = $row[0]; $from_person = $row[1]; $from_mobile = $row[2]; $query = mysql_query("SELECT customer_id FROM campaign_summary WHERE camp_id='$camp_id'") or die(mysql_error()); $row = mysql_fetch_row($query); $cusid = $row[0]; $query = mysql_query("SELECT email FROM client_info WHERE comp_id='$cusid'") or die(mysql_error()); $row = mysql_fetch_row($query); $toer = $row[0]; include 'library/closedb.php'; ?> <table width="100%" border="0"> <tr><td rowspan="4"><input type="submit" name="send_email" id="send_email" style="height:50px; width:100px;" value="SEND" onClick="return err_check();" /></td><td><span class="que">From : </span></td><td colspan="3"><?php echo $from_email; ?><input type="hidden" name="from_mail" id="from_mail" /><input type="hidden" name="camp_id" id="camp_id" value="<?php echo $camp_id;?>"/></td></tr> <tr><td><span class="que">To : </span></td><td colspan="3"><input name="to_email" id="to_email" style="width:250px;" value="<?php echo $toer;?>"/></td></tr> <tr><td><span class="que">CC : </span></td><td colspan="3"><input name="cc_email" id="cc_email" style="width:250px;"/></td></tr> <tr><td><span class="que">Subject : </span></td><td colspan="3"><input style="width:300px;" name="subject" id="subject" /></td></tr> <tr><td rowspan="1" colspan="2"> </td><td><input type="checkbox" name="ori_pdf" id="ori_pdf" checked /> PDF Quotation</td><td> </td><td> </td></tr><tr><td colspan="2"><span class="que">Credit Application</span></td><td><input type="checkbox" name="corporate" id="corporate"/>Corporate</td><td><input type="checkbox" name="individual" id="individual" />Individual</td><td><input type="checkbox" name="cash" id="cash" />Cash Account</td> </tr> <tr> <td colspan="2" rowspan="3"></td><td><input type="checkbox" name="tabloid" id="tabloid" />Tabloid Example</td> <td><input type="checkbox" name="broadsheet" id="broadsheet" />Broadsheet Example</td></tr> <tr><td><input type="checkbox" name="colmt" id="colmt" />Column Sizes Tabloid</td> <td><input type="checkbox" name="colmb" id="colmb" />Column Sizes Broadsheet</td></tr> <tr><td><input type="checkbox" name="maps" id="maps" />Maps / Distribution</td><td colspan="2" align="right">External Attachments <input id="upload_file" name="upload_file" type="file"/> </td></tr> <tr><td colspan="2"><span class="que">Message :</span></td><td colspan="3"> <textarea id="elm1" name="elm1" rows="15" cols="80" style="width: 100%"> <?php echo "<br><br><br>" . $from_person . "<br>" . $from_mobile; ?> </textarea> </td></tr> </table> </form> </body> </html> Hello, I used a standard orderform which I expanded. With this form people can order some products. But when I submit the form with data from a javascript the mail is empty. Can anyone help? I am just a beginner.... You can try the form here Thanks in advance! Hein. HTML: Code: <script src="./include/js/drinkValidation.js" type="text/javascript"></script> <form name="add-drinks" action="include/add-drink.php" method="POST" onSubmit="return addDrinkFormValidation(this);" enctype="multipart/form-data" > <span id="colour" class='modify_form'> <label for='drinkColour'>Spirit Colour:</label> <br /> <select name='drinkColour' tabindex=1> <option value='' >None</option> <option value='R' >R</option> <option value='G' >G</option> <option value='Y' >Y</option> </select> </span> <div class='modify_form'> <label for='drinkType'>Type:</label> <br /> <select name='drinkType' tabindex=1 onChange="HideObjects(this.value)"> <option value="">Select a Drink type:</option> <option value='Cask' >Cask Ales</option> <option value='Guest' >Guest Ale</option> <option value='Lager' >Lager</option> <option value='Bottled Beers' >Bottled Beer</option> <option value='Wines' >Wine</option> <option value='Ciders' >Cider</option> <option value='Softs' >Soft</option> <option value='Spirits' >Spirit</option> </select> </div> <div id="drinkABV" class='modify_form'> <label for='drinkABV'>ABV:</label> <br /> <input name='drinkABV' size='2' tabindex=4 maxlength="4" placeholder="ie: 4.2"/> <label for='drinkABV'>%</label> </div> <div id="name"class='modify_form'> <label for='name'>Name:</label> <br /> <input name='name' size='25' tabindex=3 placeholder="Drink name"/> </div> <div id="drinkInfo" class='modify_form'> <label for='drinkInfo'>Description:</label> <br /> <textarea name='drinkInfo' rows='5' cols='30' maxlength='255' tabindex=5 placeholder="Max 255 characters"></textarea> </div> <div id="pint" class='modify_form'> <label for='drinkPintPrice'>Pint (£):</label> <br /> <input name='drinkPintPrice' size='10' tabindex=8 /> </div> <div id="halfpint" class='modify_form'> <label for='drinkHalfPrice'>Half Pint (£):</label> <br /> <input name='drinkHalfPrice' size='10' tabindex=7 /> </div> <div id="drinkSpecialPrice" class='modify_form'> <label for='drinkSpecialPrice'>Offer Price (£):</label> <br /> <input name='drinkSpecialPrice' size='10'tabindex=6 /> </div> <div id="drinkbottlePrice" class='modify_form'> <label for='drinkbottlePrice'>Bottle/Spirit Price (£):</label> <br /> <input name='drinkbottlePrice' size='10'tabindex=6 /> </div> <br /> <br /> <input type="file" name="cons_image" /> <br /> <br /> <div id='submit'> <input type='submit' value='Add New Drink' /> </div> <br /> <p><b>Please add the information you wish to add then click Add New Drink</b></p> </form> Javascript containing validation Code: var ck_abv = /[0-9]{1,2}\\.[0-9]{1}$/; var ck_price = /[0-9]{1,2}\\.[0-9]{2}$/; var ck_name = /^[A-Za-z0-9 ]{3,20}$/; var ck_info = /^[A-Za-z0-9 ]{3,255}$/; alert ("Im in the file"); function addDrinkFormValidation(form){ var type = form.drinkType.value; var abv = form.drinkABV.value; var name = form.name.value; var info = form.drinkInfo.value; var pint = form.pint.value; var halfpint = form.halfpint.value; var bottle = form.drinkbottleprice.value; var offer = form.drinkSpecialprice.value; var errors = []; alert (form); alert (type); alert (abv); alert (info); alert (pint); alert (halfpint); alert ("Anything showing"); if(type==0){ errors[errors.length] = "Please select a drink type."; } if(!ck_name.test(name) || (name == "")){ errors[errors.length] = "Please enter a drink name."; } if(!ck_info.test(info) || (info == "")){ errors[errors.length] = "Please enter a drink description."; } if(!ck_abv.test(abv)){ errors[errors.length] = "Illegal character in ABV"; } if(!ck_price.test(pint)){ errors[errors.length] = "Illegal character in pint"; } if(!ck_price.test(halfpint)){ errors[errors.length] = "Illegal character in halfpint"; } if(!ck_price.test(bottle)){ errors[errors.length] = "Illegal character in Bottle/Spirit Price"; } if(!ck_price.test(offer)){ errors[errors.length] = "Illegal character in Offer price"; } if (errors.length > 0) { reportErrors(errors); return false; } return false; } function reportErrors(errors){ var msg = "Please Enter Valid Data...\n"; for (var i = 0; i<errors.length; i++) { var numError = i + 1; msg += "\n" + numError + ". " + errors[i]; } alert(msg); } For some reason i dont know why the javascript isnt reading the function even tho they are correctly named, the file is being read as the 1st test alert comes up. the 2nd one inside the function doesnt know. can anyone point in the right place or show me where i am going wrong. as you can see i have put both my entire form and and the java file up. so you can easily see what goes on #on a note i have multiple forms in a tab system if that has anything to do with it although i shouldnt see why it should. #oh and did i get my regex correct for ck_price e.g "9.99 or 10.99" and ck_abv eg "4.2 or 10.2 or 34" #im also using wampserver 2.1 with win7 and chrome if it's needed thanks ste I want to use Javascript to submit a form - without filling the form in physically Is this possible? Let's say a web page has a form that submit First Name and Last Name to the next page Instead of filling in the form and hitting submit, can I submit the data in variables and call the next page somehow using Javascript? Thanks OM I have trying to save an update the xml file which is there in same folder in which HTML page is there. In HTMl page i have written javascript code to Save and Update XML on server.The code is like this Code: function Save() { var xmlDoc= new ActiveXObject("MSXML.DOMDocument") xmlDoc.async="false" xmlDoc.load("/show/Share%20Workspace/Nidhi/Share%20%Document/Account.xml") //..code to modify xmlDoc xmlDoc.save ("/show/Share%20Workspace/Nidhi/Share%20%Document/Account.xml") xmlDoc = null; alert('Details saved'); } When i am accessing HTMl page on server from client and this function is called error 'Parameter is incorrect' is showing on line Code: xmlDoc.save ("/show/Share%20Workspace/Nidhi/Share%20%Document/Account.xml") Note: xmlDoc.load("/show/Share%20Workspace/Nidhi/Share%20%Document/Account.xml") is working fine. The save is working fine in local but not when on server and request from client. Kindly suggest me the possible solution to it. Hello Friends In my jsp,Struts project i am using the javascript calendar control for selecting the date and by using function calcage() i am calculating the age of the user but problem occurs when the page refreshes OR when user updated the other values such as name ,contact no. Then the value of the age is set as 0 in the textfield as 0 So can you please tell me why this problem occurs And please give me solution Thanks Hi all, I've been trying to set, get and delete js cookies for a while now, although they seem to set (from what I can tell) I can't seem to do what else I need with them. This is what I'm trying to do: Function1 - setCookie (sets a cookie called 'saveAndExit' - that's it, no expiry date) Function2 - useCookie (checks to see if a cookie called 'saveAndExit' exists and if it does alert("COOKIE WORKS") and then deletes the cookie If it doesn't exist alert("cookie does not exists") Could anyone assist with this? It's been driving me insane for days! Thanks. Hello everyone! I am having really tough time learning JavaScript Cookies! Can somebody explain me how to use them? "Please do not provide any external links! It is a request!" Any type of basic lesson/advice/suggestion will be quite helpful to me. Thanks! Hi I am very new to JavaScript. Please help me to get my code working. I want to store user preferences with cookie. With two buttons, to increase and decrease the font size. The following is my code to create cookies and check cookies. But I am lost with the buttons and other coding. Please help me.. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript"> function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires; } function checkCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function fsize(size,unit,id){ var vfontsize = document.getElementById("text1"); if(vfontsize){ vfontsize.style.fontSize = size + unit; createCookie("textsizestyle", textsize, 365); } } var cookie = readCookie("textsizestyle"); textsize = cookie ? cookie : 10; fsize(textsize,'px','content'); </script> </head> <body> <label> Change this font according to button click </label><br /> <input type="button" id="text1" value=" small" onclick="fsize()"/> <input type="button" id="text2" value="big" onclick="fsize()"/> </body> </html> Thanks hello to everyone i need a way to create a cookie based on user selection from a dropdown list and a radio button set . from the drop down list i control var city (1,2,3...) and from the radio buttons dow(f,s) , cdate(a,b,c,...) , ctime (a,b,c,...) it is a clock format and i want in the first page when the user select's the format that he wants it will remain in every page until he leaves the site Thankz Hi I am working on a .net basket where I save the info for the products in the basket etc in a cookie. Now I have an html button on the basket page where I want to be able to delete the product (Cookie). I am using Code: <script type="text/javascript"> function delete_cookie ( cookie_name ) { expires = Now(); document.cookie = cookie_Name+"= ;expires="+expires.toGMTString(); } </script>But I get an error that says the cookie is not delcared? But it does exist because I retrive the name of the cookie when looping through the cookie list. What am I doing wrong here? hy guys I have this Ad Script script: <HEAD> section Code: <style type="text/css"> <!-- #sponsorAdDiv {position:absolute; height:1; width:1px; top:0; left:0;} --> </style> <script type="text/javascript"> adTime=10; // seconds ad reminder is shown chanceAd=1; // ad will be shown 1 in X times (put 1 for everytime) var ns=(document.layers); var ie=(document.all); var w3=(document.getElementById && !ie); var calunit=ns? "" : "px" adCount=0; function initAd(){ if(!ns && !ie && !w3) return; if(ie) adDiv=eval('document.all.sponsorAdDiv.style'); else if(ns) adDiv=eval('document.layers["sponsorAdDiv"]'); else if(w3) adDiv=eval('document.getElementById("sponsorAdDiv").style'); randAd=Math.ceil(Math.random()*chanceAd); if (ie||w3) adDiv.visibility="visible"; else adDiv.visibility ="show"; if(randAd==1) showAd(); } function showAd(){ if(adCount<adTime*10){adCount+=1; if (ie){documentWidth =truebody().offsetWidth/2+truebody().scrollLeft-20; documentHeight =truebody().offsetHeight/2+truebody().scrollTop-20;} else if (ns){documentWidth=window.innerWidth/2+window.pageXOffset-20; documentHeight=window.innerHeight/2+window.pageYOffset-20;} else if (w3){documentWidth=self.innerWidth/2+window.pageXOffset-20; documentHeight=self.innerHeight/2+window.pageYOffset-20;} adDiv.left=documentWidth-200+calunit;adDiv.top =documentHeight-200+calunit; setTimeout("showAd()",100);}else closeAd(); } function closeAd(){ if (ie||w3) adDiv.display="none"; else adDiv.visibility ="hide"; } function truebody(){ return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body } onload=initAd; //End--> </script> right above the </BODY> Code: <div id="sponsorAdDiv" style="visibility:hidden"> <table width="450px" height="350px" bgcolor="#008000"><tr><td> <table width="445px" height="345px" bgcolor="#F0FFF0"><tr><td align="center" valign="middle"> <!--*****EDIT THIS MESSAGE*****--> <!--*****EDIT THE ABOVE MESSAGE*****--> </td></tr></table></td></tr></table> </div> And i trying to find a way to show a div with text and images just once per day using cookies....i like something like this http://javascript.internet.com/cooki...opup-once.html but not with popup. I am trying to make it when a user comes to a site, if they have been there before an alert box will open saying "Welcome firstname, lastname, and email address". Right now I can get the code to work to show a first name, but when I try to get it to also show the last name and email I get an error or something like "Welcome NaN NaN, NaN". Here is the code I have right now. Code: function confirmSubmission() { var confirmed = validateData(); return confirmed; }//confirmSubmission function validateData() { if (document.forms[0].elements[1].value == "") { alert("You must enter a first name."); document.forms[0].elements[1].focus(); return false; }//blank first name if (document.forms[0].elements[2].value == "") { alert("You must enter a last name."); document.forms[0].elements[2].focus(); return false; }//blank last name if (document.forms[0].elements[3].value == "") { alert("You must enter an address."); document.forms[0].elements[3].focus(); return false; }//blank address if (document.forms[0].elements[4].value == "") { alert("You must enter a city."); document.forms[0].elements[4].focus(); return false; }//blank city if (document.forms[0].elements[5].value == "") { alert("You must enter a state."); document.forms[0].elements[5].focus(); return false; }//blank state if (document.forms[0].elements[6].value == "") { alert("You must enter a zipcode."); document.forms[0].elements[6].focus(); return false; } else { if (/...../.test(document.forms[0].elements[6].value) == false) { alert("You must enter a valid zipcode."); document.forms[0].elements[6].focus(); return false; } }//blank zip if (document.forms[0].elements[7].value == "") { alert("You must enter an e-mail address."); document.forms[0].elements[7].focus(); return false; } else { if (/@/.test(document.forms[0].elements[7].value) == false || (document.forms[0].elements[7].value).indexOf(".", (document.forms[0].elements[7].value).indexOf("@")) == -1) { alert("You must enter a valid e-mail address."); document.forms[0].elements[7].focus(); return false; } }//blank email if (document.forms[0].elements[8].value == "" || document.forms[0].elements[9].value == "" || document.forms[0].elements[10].value == "") { alert("You must enter a telephone number."); document.forms[0].elements[8].focus(); return false; } else { if (/.../.test(document.forms[0].elements[8].value) == false) { alert("You must enter a valid area code."); document.forms[0].elements[8].focus; return false; }//area code else if (/.../.test(document.forms[0].elements[9].value) == false) { alert("You must enter a valid telephone exchange."); document.forms[0].elements[9].focus; return false; }//NNX else if (/..../.test(document.forms[0].elements[10].value) == false) { alert("Your number must be four characters."); document.forms[0].elements[10].focus; return false; }//number }//blank telephone setCookie('username', document.forms[0].elements[1].value, 2); return true; }//validateData function setCookie(c_name, value, expiredays) { var expDate=new Date(); expDate.setDate(expDate.getDate() + expiredays); document.cookie=c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + expDate.toUTCString()); And on another page I have: Code: function checkCookie() { username = getCookie('username'); if (username != null && username != "") alert('Welcome back, ' + username + '!'); }//checkCookie function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start + c_name.length + 1; c_end = document.cookie.indexOf(";", c_start); if (c_end == -1) c_end=document.cookie.length; return unescape(document.cookie.substring(c_start, c_end)); } } return ""; } Any help would be appreciated. I'm more of an actionscript person but got roped into an html/javascript job. What I need to do, and it shouldn't be that difficult is this: page1.html - there is a yellow button and a red button - if the user clicks on the yellow button I want to set a cookie with the value "yel" then load the next page - if they click the red button set that cookie with the value "red" page2.html - 'onload' i want to read that cookie and load up the main image to match, something like this maybe?... document.mainimage.src='img/main_' + variable + '.png' so that the path would be for example 'img/main_red.png' Any help please? Preferably javascript only and as simple as possible. If you think this would be easier sending that variable in the URL instead of as a cookie please explain. I'm having a very hard time searching for tutorials that are any good and that do exactly this kind of thing. I've looked on several websites and several threads here regarding writing and reading cookies with javascript, and I just can't seem to get it to work. All I want is a simple text box with 2 buttons: Save and Recall. Text entered into box is saved to a cookie when "Save" is pressed, and at a later date when "Recall" is pressed the saved text will show up in the box. Can you help please? I'm running into a bit of problems trying to use some JS cookies. I have 2 values I want stored and have created the following set cookie function
Code: setCookie(Name, amountCorrect, totalAmountCorrect, max-age) { document.cookie = "averageScore" + quizAverageIncrement + totalCorrect +"; max-age=" + 1000 * 60 * 60 * 24 * 30 +"; path=/; } Now I want to read the cookie and use the values from the two variables "averageScore" and "quizAverageIncrement" I'm not sure exactly how to be able to use the values of those two variables since they have been concatenated into a string when the cookie is made (I think). So I would like to start with Code: function getCookie(averageScore) { // if cookie is blank on first iteration do nothing else retrieve values I need. \n if (document.cookie.length > 0 Thats all I have please point me in the right direction to retrieve these values and use them in my JS elsewhere. Hi... is there a way to create iframes using cookies and javascript ? What i need to do is to have a way to create a cookie on page one, and use the info on page two to create the iframe. Users will see a list of "external links", once they click on a link, they will be redirected to a page that will generate a iframe of the chosen link. My guess is that if there is a way, it must need to use cookies to store the info (url) to get used by the script that will create the iframe on the page that will be used to show all iframes. Any ideas or help with this will be apriciated. Sorry for my poor english. Hello guys! I have a jquery fancybox that pop's up on exit (using onbeforeunload), now i want it to show only once so i tried doing it with cookies but i just can get it to work. this is my script so far hope you can help me with this, Thanks! Code: <script type="text/javascript"> function PopIt() { if (document.cookie.length == 0) { var exdate=new Date(); exdate.setDate(exdate.getDate()+7); document.cookie="cook=yes" + ";expires="+exdate.toUTCString(); $("a#trigger").trigger('click'); window.onbeforeunload = UnPopIt; return "Before you leave:\nPlease take a few seconds to answer 2 questions\nso we can better assist you and others in the future. \nThanks!"; } } function UnPopIt() { /* nothing to return */ } $(document).ready(function() { window.onbeforeunload = PopIt; $("a#trigger").fancybox({ 'hideOnContentClick': false, 'showCloseButton': true }); $("a[id!=trigger]").click(function(){ window.onbeforeunload = UnPopIt; }); }); </script> |