JavaScript - Writing And Reading Cookies With Javascript
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? Similar TutorialsI'm sorry I'm not to good at javascript. I know VB.net, but I have not learned javascript yet, and I need some help. I am working on a project to get a survey to pop up for new visitors on the index page of our site. What I need to do: on load look for a cookie, if that cookie is not found run a script telling the site to pull up another page in lightview using its own "on load" command. If the cookie is there the site will not open this other page. What I've done: I already found a way to do most of this, but I can only use a hyper link as a trigger for the site to load the other page in lightview. Here is a link of what I have so far: http://naomi-dr.com/template2.html Please let me know if you have any questions or need more information. Hi there! I'm having a little bit of trouble, I've read through tutorials on parsing XML to Javascript and such, but the XML file I'm working with is very different to the ones the tutorial showed me. Normally it'd be like Code: <here> <there></there> </here> But the one I'm wanting to work in looks like this: Code: <rowset name="names" columns="name"> <row name="this"> <rowset name="fun" columns="name"> <row name="that"> </rowset> </row> </rowset> To make it more clear, my question to you is: How can I parse <row name="that"> where only we only have <row name="this"> Hello, I am a novice and am hoping I can get some help here. I am self taught at basic HTML and am now trying to add some "v v vroom!" to a site that I am developing. The problem I am faced with is I have a Javascript that I am using as an experiment to see how Javascript works (in the hope that I can use other more exiting Javascripts on my sight I am buliding). I have copied it onto NotePad from a self teaching book which when opened up in a browser does not work. The script in question is; <html> <head> <title>My First Javascript page</title> <script type="text/javascript"></script> <style type="text/css"> body {document.bgcolor="pink"} </style> <body> This is my first Javascript page !! So **** off! <form> <input type="button" onclick="document.bgcolor='blue'" name="change" value="blue"> <input type="button" onclick="document.bgcolor='red'" name="change" value="red"> <input type="button" onclick="document.bgcolor='yellow'" name="change" value="yellow"> <input type="button" onclick="document.bgcolor='white'" name="change" value="white"> <input type="button" onclick="document.bgcolor='fuchsia'" name="change" value="fuchsia"> </form> </body> </html> Can anyone shed any light on what I might be doing wrong, or what I can do to make it work? Thank you all in advance. David Hood. I want to write an xml stream to the browser using javascript. What I am currently getting is the visual data and the page source is the xml stream. What I would like to get is a visual representation of the xml as well as the underlying page source. Further information. The visual presentation wanted is: <?xml version="1.0" encoding="UTF-8" ?> - <FSResult> <FoodStampAllotment>526</FoodStampAllotment> <GrossEligible>TRUE</GrossEligible> <NetEligible>TRUE</NetEligible> <AssetEligible>TRUE</AssetEligible> </FSResult> The page source for that is: <?xml version="1.0" encoding="UTF-8" ?><FSResult><FoodStampAllotment>526</FoodStampAllotment><GrossEligible>TRUE</GrossEligible><NetEligible>TRUE</NetEligible><AssetEligible>TRUE</AssetEligible></FSResult> The page url includes: FSCalcServlet.do The other visual presentation that we want to look like the above: 150TRUETRUETRUE The other page source is: <?xml version="1.0" encoding="UTF-8" ?><FSResult><FoodStampAllotment>150</FoodStampAllotment><GrossEligible>TRUE</GrossEligible><NetEligible>TRUE</NetEligible><AssetEligible>TRUE</AssetEligible></FSResult> The other page url includes: FSCalc.html This version is written from Flex via javascript and the original is a java servlet. hi, (JAVASCRIT) the actual program reads and prints values from a checkbox tree and this piece of code does it. Code: dhtmlXTreeObject.prototype.getAllChecked=function(){ return this._getAllChecked("","",1); } dhtmlXTreeObject.prototype.getAllCheckedBranches=function(){ return this._getAllChecked("","",0); } dhtmlXTreeObject.prototype._getAllChecked=function(htmlNode,list,mode){ if(!htmlNode)htmlNode=this.htmlNode; if(((mode)&&(htmlNode.checkstate==1))||((!mode)&&(htmlNode.checkstate>0))){if(list)list+=","+htmlNode.id;else list=htmlNode.id;} var j=htmlNode.childsCount; for(var i=0;i<j;i++) { list=this._getAllChecked(htmlNode.childNodes[i],list,mode); }; if(list)return list;else return ""; }; the values are returned to alertbox. Code: <a href="javascript:void(0);" onclick="alert(tree2.getAllChecked());">Get list of checked</a><br><br> kindly help me with reading the returned values in to an array or list (but bot in alertbox) ...so that i can pass them to next JSP page. waiting for ur answer, BeanBoy ! Somebody had posted this query on how to read text files using JavaScript.......can't find that post now... Anyways, though it's not possible to read text-files using JavaScript it is possible to read XML files using it. Here is an XML based JavaScript Ticker http://www.dynamicdrive.com/dynamicindex2/xmlticker.htm It works only on browsers supporting XML (IE) Enjoy! i have borrowed a java script to produce a weather forecast using data from my weather station. Quote: //code to get your variables goes here //I've assumed they a // $sager_wind = wind direction // $sager_rumbo = wind change // $sager_hpa = Baro value // $sager_trend = Baro trend // $sager_nubes = Sky condition //now we can prepare them for the Sager script //the sager script wants uppercase, so just to be sure... $sager_wind = strtoupper($sager_wind); //has to be uppercase $sager_rumbo = strtoupper($sager_rumbo); //allow for either of mB or Hg input if ($sager_hpa > 50) { $sager_hpa = $sager_hpa * 0.0295300;} //enumerate the Baro switch ($sager_hpa) { case ($sager_hpa > 30.4): $sager_hpa = 1; break; case ($sager_hpa > 30.1): $sager_hpa = 2; break; case ($sager_hpa > 29.9): $sager_hpa = 3; break; case ($sager_hpa > 29.7): $sager_hpa = 4; break; case ($sager_hpa > 29.5): $sager_hpa = 5; break; case (sager_hpa > 29.2): $sager_hpa = 6; break; case (sager_hpa > 28.: $sager_hpa = 7; break; case (sager_hpa > 28.0): $sager_hpa = 8; break; } //enumerate the Baro trend if (strcasecmp($sager_trend, 'Rising Rapidly') == 0) { $sager_trend = 1; } if (strcasecmp($sager_trend, 'Rising Slowly') == 0) { $sager_trend = 2; } if (strcasecmp($sager_trend, 'Steady') == 0) { $sager_trend = 3; } if (strcasecmp($sager_trend, 'Falling Slowly') == 0) { $sager_trend = 4; } if (strcasecmp($sager_trend, 'Falling Rapidly') == 0) { $sager_trend = 5; } //enumerate the Sky condition if (strcasecmp($sager_nubes, 'Clear') == 0) { $sager_nubes = 1; } if (strcasecmp($sager_nubes, 'Partly Cloudy') == 0) { $sager_nubes = 2; } if (strcasecmp($sager_nubes, 'Mostly Overcast') == 0) { $sager_nubes = 3; } if (strcasecmp($sager_nubes, 'Overcast') == 0) { $sager_nubes = 4; } if (strcasecmp($sager_nubes, 'Rain') == 0) { $sager_nubes = 5; } ?> <html> <!-- standard header stuff goes here --> <!-- and don't forget to include the sager script --> <script src="sager_cast.js" type="text/javascript"></script> <body> <br /> Sager = <span id="forecast">forecast will appear here</span> <script type="text/javascript" language="javascript"> <!-- { //we could do some fancy escaping to directly insert the php variables //into the javascript function call, but this is harder to break. z_wind = "<?php echo $sager_wind?>"; z_rumbo = "<?php echo $sager_rumbo?>"; z_hpa = <?php echo $sager_hpa?>; z_trend = <?php echo $sager_trend?>; z_nubes = <?php echo $sager_nubes?>; document.getElementById('forecast').innerHTML = sager_cast( z_wind, z_rumbo, z_hpa, z_trend, z_nubes); } //--> </script> </body> </html> this basically turns my PHP variables intoa forecast by using the script above and also sager_cast.js (which crunches the numbers). my question is how can i record the output to a text file ie. this bit Quote: <br /> Sager = <span id="forecast">forecast will appear here</span> i know how to run a cron job on my host server but whenever i try to use php to geta at it, it fails. i understand that php and JS and side server / client server / host server different, but surely there must be a way to record the output using my host and the script that i have. my goal is to catch the forecast every 15 mins (with a time stamp) and then look back at the (text) file to see how it has changed. can anyone please help? one suggestion is to turn the number crunching JS script into php so i can 'get at it' but there are thousands of lines of code! thanks in advance, and hello from a newbie poster! 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! 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 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 Q1. write a function called countAS that will take a string as input (using a prompt dialog box,prompt the user or the string).the string must contain only a's,b's and c's e.g. "abccbbaa" or "aaabbbccc" if any other letters are present apart from the letters a b c, output an alert dialog box with an error message and prompt the user again to input a valid string.count the number of a's the numbers of b's and the numbers of c's entered and display the count for each as well as a total count of all the characters within the string . for example if the string was abbcc output should be as follows: the total count is 5 characters The Number of a's is 1 The Number of b's is 2 The Number of c's is 2 Q2. write a code that uses an event handler to display an alert dialog box with the message 'hello to you all' when a user clicks a link in a html page which links to the school of computing website. Hi, I haven't really done any JavaScript programming and need help writing a couple of functions for a very basic sudoku game I am trying to build. Basically I want it to highlight which in green the correct answers and red the wrong ones. The names of the input fields of the table cells are the correct answer so I need a function that will compare the name of and input with the value, if the match then change the cell green, if not turn it red. Bellow is the code i have written with unessecary parts taken out Code: <?php $level = array ( "Easy" => array ("9","4","6","2","8","7","3","5","1","5","8","3","6","1","9","7","4","2","2","1","7","5","4","3","6","9","8","8","6","5","4","3","2","1","7","9","7","2","1","9","6","5","4","8","3","4","3","9","1","7","8","5","2","6","6","7","8","3","2","4","9","1","5","3","9","4","8","5","1","2","6","7","1","5","2","7","9","6","8","3","4"), "Medium" => array ("6","5","9","8","2","4","3","1","7","4","3","1","5","9","7","8","2","6","8","7","2","1","3","6","9","5","4","2","6","5","9","4","8","7","3","1","1","9","7","6","5","3","4","8","2","3","4","8","7","1","2","6","9","5","9","2","6","4","8","5","1","7","3","7","1","3","2","6","9","5","4","8","5","8","4","3","7","1","2","6","9"), "Hard" => array ("9","8","3","7","2","1","6","5","4","7","6","5","8","4","9","3","2","1","1","2","4","3","6","5","7","9","8","8","1","7","9","5","6","2","4","3","3","4","6","2","1","8","5","7","9","5","9","2","4","7","3","1","8","6","6","7","8","5","3","4","9","1","2","4","5","1","6","9","2","8","3","7","2","3","9","1","8","7","4","6","5") ); $mask = array ( "Easy" => array ("0","4","6","2","8","0","0","0","0","5","0","0","6","0","0","7","4","0","2","0","0","0","0","0","0","0","0","0","0","5","0","3","2","0","7","0","0","2","1","0","0","0","4","8","0","0","3","0","1","7","0","5","0","0","0","0","0","0","0","0","0","0","5","0","9","4","0","0","1","0","0","7","0","0","0","0","9","6","8","3","0"), "Medium" => array ("0","0","0","8","0","0","0","1","7","4","3","0","0","0","0","0","0","0","0","0","2","0","0","0","9","0","0","2","0","0","0","0","8","0","0","0","0","9","7","6","0","3","4","8","0","0","0","0","7","0","0","0","0","5","0","0","6","0","0","0","1","0","0","0","0","0","0","0","0","0","4","8","5","8","0","0","0","1","0","0","0"), "Hard" => array ("9","0","0","0","0","1","0","5","0","7","6","5","0","0","0","0","0","0","1","0","0","3","0","0","0","0","8","0","0","0","0","0","6","0","4","0","0","0","0","2","1","8","0","0","0","0","9","0","4","0","0","0","0","0","6","0","0","0","0","4","0","0","2","0","0","0","0","0","0","8","3","7","0","3","0","1","0","0","0","0","5") ); $difficulty = $_GET["difficulty"]; $style = $_GET["style"]; ?> <!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> <script src="sudoku.js" language="javascript" type="text/javascript"></script> </head> <body> <div id="wrap"> </div> <div id="nav"> <div class="option-item"> <form action="index.php" method="get"> <input type="submit" name="difficulty" value="Easy" /> <input type="submit" name="difficulty" value="Medium" /> <input type="submit" name="difficulty" value="Hard" /> </form> </div><input type="button" class="control-button" onclick="checkStatus()" value="How am I Doing?" /> </div> <div id="main"> <form name="f"> <?php $box = $mask[$difficulty]; ?> <table class="root-table"> <tr> <td> <table class="box box-one"> <tr> <td><input type="text" size="1" name="<?php echo $level[$difficulty][0]; ?>" value="<?php if ($mask[$difficulty][0] > 0) echo $mask[$difficulty][0]; ?>" /></td> <td><input type="text" size="1" value="<?php if ($mask[$difficulty][1] > 0) echo $mask[$difficulty][1]; ?>" /></td> <td><input type="text" size="1" value="<?php if ($mask[$difficulty][2] > 0) echo $mask[$difficulty][2]; ?>" /></td> </tr> <tr> <td><input type="text" size="1" value="<?php if ($mask[$difficulty][9] > 0) echo $mask[$difficulty][9]; ?>" /></td> <td><input type="text" size="1" value="<?php if ($mask[$difficulty][10] > 0) echo $mask[$difficulty][10]; ?>" /></td> <td><input type="text" size="1" value="<?php if ($mask[$difficulty][11] > 0) echo $mask[$difficulty][11]; ?>" /></td> </tr> <tr> <td><input type="text" size="1" value="<?php if ($mask[$difficulty][18] > 0) echo $mask[$difficulty][18]; ?>" /></td> <td><input type="text" size="1" value="<?php if ($mask[$difficulty][19] > 0) echo $mask[$difficulty][19]; ?>" /></td> <td><input type="text" size="1" value="<?php if ($mask[$difficulty][20] > 0) echo $mask[$difficulty][20]; ?>" /></td> </tr> </table> Hi I have written the following code to read contents of a text file using FileReader object of HTML 5 for Google Chrome. Quote: <script> function handle_files(files) { var i; if (checkBrowser("Chrome")) { for (i = 0; i < files.length; i++) { file = files[i]; var reader = new FileReader(); ret = []; reader.onload = function (e) { console.log(e.target.result) } reader.onerror = function (stuff) { console.log("error", stuff) console.log(stuff.getMessage()) } text = reader.readAsText(file[i]); alert(text); } } } </script> ---------------------- <input type="file" multiple="multiple" onchange="handle_files(this.files)"> Unfortunately, the variable text always displays as undefined. Everything above the line text = reader.readAsText(file[0]); works fine. How can I fix it?. Or is there any other solution to read a text file using HTML5/JavaScript on Chrome? Thanks in advance. 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. Writing Table Cells and Switch Statements I am to create a function and purpose is to write blank tables cells to make up horizontal bar. function will have 2 parameters=(partyType and percent partyType parameter stores variables of D,R,I,G or L percent parameter store percentage rounded to nearest integer so I am to make a switch and break statements /commands then have to create a For Loop in counter variable goes up from 1 through value of parmeter increments of 1 heres the code I created for this one Code: function createBar(partyType,percent){ // script element to create blank cells switch(partyType) { case "D": document.write("<td class='dem'></td>"); break; case "E": document.write("<td class='rep'></td>"); break; case "I": document.write("<td class='ind'></td>"); break; case "G": document.write("<td class='green'></td>"); break; case "L": document.write("<td class='lib'></td>"); break; } var barText = partyType for (i=0; i < percent; i++) { document.write(barText); So what improvements should I make? should my loop be before everything? Thanks 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. 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> 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. |