JavaScript - Retrieving Cookie Values
I had post this problem before, dealing with the shopping cart application. The application so far does everything that i would like it to do. I'm able to store and retrieve the cookies. But right now, my problem is extracting the individual values from the cookies and placing them into a table i have created. This is the format of the cookie when retrieved.
ItemName = quantity$price. what i am trying to do is retrieve the quantity and price values from the cookie, and display that data into my table. the cookie is being created in my store page, and then retrieved and displayed in my cart page. here is the code for my store page store.html 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" xml:lang="en" lang="en"> <head> <title> Store </title> <h1> My store </h1> <script type="text/javascript"> function retr(circle) { var cke = document.cookie.split(';'); var nameCk= name + "="; for(var i=0; i < cke.length; i++) { var c = cke [i]; while (c.charAt(0)==' ') c = c.substring(1, c.length); if (c.indexOf(nameCk) == 0) return c.substring(nameCk.length, c.length); } return null; } function createCookie() { var exdate = new Date(); exdate.setDate(exdate.getDate() +10); if (document.getElementById("circle").checked) { document.cookie = "Circle=" + document.getElementById ("quantity1").value + document.getElementById("price1").value + ";expires="+exdate.toGMTString(); } } function retrieve() { if (document.getElementById("circle").checked) { document.getElementById("ret").value = document.cookie; } } function Calc() { var fpri = document.getElementById("price1").value; var pri = fpri.substr(1); var qty = document.getElementById("quantity1").value; var spri = document.getElementById("price2").value; var pri2 = spri.substr(1); var qty2 = document.getElementById("quantity2").value; if (document.getElementById("circle").checked) { document.getElementById("total").value ='$' + Number(pri) * Number(qty); } else document.getElementById("total").value = '$' + Number(pri2) * Number(qty2); } </script> </head> <body> <table border = "1"> <tr> <td> <input type="checkbox" id="circle" /> Circle </td> <td> <img src="circle.jpg"> </img> </td> <td> Price: <input type="text" size="4" value = "$10.00" id="price1" name = "price1" /></td> <td> Quantity: <input type="text" size = "4" id="quantity1"/></td> </tr> <tr> <td> <input type = "checkbox" id="stickman" /> Stickman </td> <td> <img src = "stickman.gif"> </img> </td> <td> Price: <input type="text" size="4" value = "$5.00" id="price2" /> </td> <td> Quantity: <input type="text" size="4" id="quantity2" /> </td> </tr> </table> <br /> <input type = "button" value = "Add to cart" onclick="createCookie()"> <br /> <br /> <a href ="cart.html" > View Cart </a> <br /> <input type = "text" size = "8" id = "total" readonly = "readonly" /> Total <br /> <input type = "button" id = "calcu" value = "calc" onclick = "Calc ()" /> <input type = "button" value = "retrieve" onclick = "retrieve()" /> <input type = "text" readonly = "readonly" name = "ret" id = "ret"/> </body> </html> the calculate and retrieve buttons, and the readonly text boxes are there just so i know the cookie is being stored and retrieved, and that i'm able to get the total, which will be displayed on my cart page. here is the code for my cart page cart.html Code: <html> <head> <title> Cart </title> <h1> My cart </h1> <script type = "text/javascript"> function retr(circle) { document.getElementById("q2").value = document.getElementById("quantity1").value } function retrieve() { var quvalue = retr("circle") if (quvalue != false) { document.getElementById("q2").value = quvalue } document.getElementById("ret").value = document.cookie; } </script> </head> <body onload = "retrieve()"> <table border = "1"> <td>Stickman </td> <td><input type = "text" size = "8" id = "q2" readonly = "readonly" /></td> <td id ="p1"> price per </td> <td id ="t1"> total </td> <tr> </tr> <td> Circle </td> <td> quantity order </td> <td> price per </td> <td> total </td> <tr> </tr> <td colspan = "3"> TOTAL: </td> <td> total price </td> </table> <br /> <br /> <input type ="text" id = "ret" readonly = "readonly" /> <br / > <br /> <input type = "button" value = "Checkout"> <br /> <br /> <a href = "store.html" > Continue Shopping </a> </body> </html> the values that are supposed to be retrieved in the table are invoked using the onload event attribute which is suppose to call the retrieve() function. Similar TutorialsI am a beginner. I am trying to create a script to randomly assign recipients to givers for a Secret Santa. The participants are placed into groups. A giver cannot be assigned a recipient with whom he is grouped. I want to return all of the assignments in a table. I have made the following script. When I run it, it seems to get stuck in a loop. Any ideas why this might be? If you have any questions about how I want this thing to run, feel free to ask. Your help would be greatly appreciated. Code: <html> <head> <script type="text/javascript"> var giver = new Array(); giver[0] = new Array("CL","BL"); giver[1] = new Array("LP","JP","BP"); giver[2] = new Array("JO","MO"); giver[3] = new Array("JC","TC"); var recipient = new Array(); recipient[0] = new Array("none","none"); recipient[1] = new Array("none","none","none"); recipient[2] = new Array("none","none"); recipient[3] = new Array("none","none"); var string = "<table><tr><td>Giver</td><td>Recipient</td></tr>"; function chooseRecipient() { var x; for (x in giver) { var y; for (y in giver[x]) { var a = Math.floor(Math.random() * giver.length); while (recipient[a].indexOf("none") < 0 || a == x) { a = Math.floor(Math.random() * giver.length); } var b = Math.floor(Math.random() * giver[a].length); while (recipient[a][b] != "none") { b = Math.floor(Math.random() * giver[a].length); } recipient[x][y] = giver[a][b]; string += "<tr><td>" + giver[x][y] + "</td><td>" + recipient[x][y] + "</td></tr>"; } } string += "</table>"; document.write(string); } </script> </head> <body onload="chooseRecipient()"> </body> </html> Hello there. I'm having trouble with cookies. I have a bunch of links that when clicked on, create a cookie. For each link I need to be able to save that cookie value to the main cookie name. Here is the click function I'm using to create the cookie: $j('a.createCookie').click(function(e) { var cookieName = "InsightsCookie"; var cookieValue = $j(this).attr("id"); $j.cookie(cookieName, cookieValue, {expires: 365, path: '/'}); }); The end result would be "InsightsCookie: cookieValue, cookieValue, cookieValue" - where each link clicked on would add a value to InsightsCookie. Any help would be much appreciated. Hi everyone, I am using a jQuery cookie script to set the cookie of some elements on my website. One of the problems is that I need the cookie to not expire after one day, I need it to expire after a while (I'm going to start off with a year). Here's my script, the red part is what I've been editing. Code: /** * Cookie plugin * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * Create a cookie with the given name and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secu true }); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain * used when the cookie was set. * * @param String name The name of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given name. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000 * 365)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } // CAUTION: Needed to parenthesize options.path and options.domain // in the following expressions, otherwise they evaluate to undefined // in the packed version for some reason... var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } }; I think this is a relatively simple problem, instead of hard coding the latitude and longitude in map.setCenter I need it to read it in from an XML file, like the the markers do below (.getAttribute("lat") and .getAttribute ("lng")). I hope this makes sense, I've tried changing the code around but I can't seem to make it work. Any help appreciated. Code: // create the map var map = new GMap2(document.getElementById("map")); map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); map.setCenter(new GLatLng( 49.4008,1.4941), 5); // Read the data from example.xml GDownloadUrl("example.xml", function(doc) { var xmlDoc = GXml.parse(doc); var markers = xmlDoc.documentElement.getElementsByTagName("marker"); for (var i = 0; i < markers.length; i++) { // obtain the attribues of each marker var lat = parseFloat(markers[i].getAttribute("lat")); var lng = parseFloat(markers[i].getAttribute("lng")); var point = new GLatLng(lat,lng); var html = markers[i].getAttribute("html"); var label = markers[i].getAttribute("label"); // create the marker var marker = createMarker(point,label,html); map.addOverlay(marker); } Hi gud mng, I have one problem... How to process textbox values/ call textbox values in JS through a Java program. My text box values are dates. I have to process these dates. Like in online banking we select day to know our transactions. After submitting we get results. remember my files are in my directory only. No need of database. My files are look like 20100929, 20100930, 20101001 For epoch_classes.js, epoch_styles.css u can download coding from this link : http://www.javascriptkit.com/script/...ch/index.shtml Code: Code: <html> <table width="900" border="0" cellpadding="10" cellspacing="10" style="padding:0"> <tr><td id="leftcolumn" width="170" align="left" valign="top"> <div style="margin-left:0px;margin-top:0px"><h3 class="left"><span class="left_h2">Select Option</span></h3> <a rel="nofollow" target="_top" href="day_wise.htm" >Day-wise</a><br /> <br /> <a rel="nofollow" target="_top" href="between.htm" >Between Days</a> <link rel="stylesheet" type="text/css" href="epoch_styles.css" /> <script type="text/javascript" src="epoch_classes.js"></script> <script type="text/javascript"> var cal1, cal2; window.onload = function () { cal1= new Epoch('epoch_popup','popup',document.getElementById('popup_container1')); cal2= new Epoch('epoch_popup','popup',document.getElementById('popup_container2')); }; /*............*/ function confirmation(f) { var startdate = f.fromdate.value var enddate = f.todate.value var myday=new Date() var yr=myday.getFullYear() var mn=myday.getMonth()+1 var dt=myday.getDate() var today="" var present, ys, ms, ds, ye,me,de, start, end if(mn < 10) { mn = "0" + mn } if(dt <10) { dt = "0" + dt } today= yr + "/" + mn + "/" + dt present=yr + "/" + mn + "/" +dt if (today < startdate ) { alert (" Start date should not be exceed to-day's date " + present ) startdate.focus() return false } if (today < enddate ) { alert (" End date should not be exceed to-day's date " + present ) enddate.focus() return false } if (today == startdate ) { alert(" You are selected to-days date as Starting day" ); } var answer = confirm("Do you want to continue ?") if (answer) { if( startdate < enddate) alert("Dates between " + startdate + " to " + enddate + " are confirmed" ) else alert("Dates between " + enddate + " to " + startdate + " are confirmed" ) } else { alert("Date not confirmed") window.location="to_date.htm"; } ys= startdate.substring(0,4); ms= startdate.substring(5,7); ds= startdate.substring(8,10); start=ys + "" + ms + "" +ds ye= enddate.substring(0,4); me= enddate.substring(5,7); de= enddate.substring(8,10); end=ye + "" + me + "" +de } /*.......................................................*/ </script> <div style="margin-left:100px;"> <body> <style type="text/css"> #conf { margin-left:115px; } </style> <td align="left" valign="top"> <table width="100" border="0" cellpadding="0" cellspacing="0"> <td style="padding-top:0px"> </table> <h4>From Date</h4> <form name= "formbet" id="placeholder" method="post" action="#" > <input id="popup_container1" type="text" name= "fromdate" maxlength="10" size="20"/> <td align="left" valign="top"> <table width="300" border="0" cellpadding="0" cellspacing="0"> <td style="padding-top:20px"> <h4>To Date</h4> <input id="popup_container2" type="text" name= "todate" maxlength="10" size="20"/> <br /> <br /> <input id="conf" type="button" onclick="confirmation(this.form)" value="Submit"> </form> </body> </html> In my coding, ys, ms, ds represents year starting, month starting, starting day... ye, me, de represents end... start,end gives file names in the format of yyyymmdd now i want to process files from 20100101 to 20100930 means from date is 2010/01/01 and to date is 2010/09/30 if i press submit button the files from 20100101 to 20100930 are processes here ys=2010 ms=01 ds =01 and ye=2010 me=09 de= 30 For this how do i call these textbox values (from date text box and todate) to another program (java) Thanks in advance. HI I have set up a page passing information.. eg anything.htm?the text and I am trying to retrieve it into a form field ie pre fill a box. What I cant seem to work is to get the text after the ? into prefilled text for the field I can print it with document.write. I am trying to get it into (or something similar) <textarea rows="4" name="products" cols="49"> XXXX here text after htm? XXXX </textarea>. Hope this makes sense and I appreciate any help and time. So basically, I have this side bar with a whole bunch of links and I wish to load content into a div directly across from it. The links will be hashes (eg example.com/#foo/bar), then the JavaScript loads the content either into a div and updates a SPAN with the page name. I only have the iFrame version so far, so can someone help me on how to improve this and actually load the content instead of an iFrame? So far I have this code: Code: <script> function goto(url) { if (location.hash != url) { window.location = url; document.getElementById("pgname").innerText = "loading..."; } } function setPage() { var hash = location.hash; if (hash=="#foo") { document.getElementById('pgname').innerHTML = 'Foo'; document.getElementById('pglocation').innerHTML = hash; window.frames['content'].location.href = "blablah/foo.php"; } if (hash=="#foo/bar") { document.getElementById('pgname').innerHTML = 'Foo</b> > <b>Bar'; document.getElementById('pglocation').innerHTML = hash; window.frames['content'].location.href = "doo/moo/23.htm"; } } </script> <body onhashchange="setPage();"> <a href="javascript: goto('#foo')">foo</a><br /> <a href="javascript: goto('#foo/bar')">foobar</a><br /> <a href="javascript: alert(location.hash + ' || ' + location);">Info</a><br /> <a href="javascript: goto(location.hash);">Goto</a><br /><br /> <b><span id="pgname">Home</span></b><br /> example.com/<span id="pglocation"></span><br /> <iframe id="content" src="index.php" /> Hello all, Sorry if this may seem like a silly question, I have searched but not really to sure how to word what I am searching for as I don't know if I am going the right way around it! Basically, I am looking to insert a keyword in to a javascript alert box when someone visits my website, so say they came from codingforums.com, it would say "Welcome, CodingForums.com Visitor". My keyword will be passed from the ad platform I am working with and shows up correctly in the tracking, so I'd imagine it's just a case of having the snippet of code for it to show in the alert, correct? If there is no keyword, I would just like it to say "Welcome Visitor" or something. How do I go about this? Thank you in advance for any help. Hi, I'm new to this forum so please forgive me on any errors I may have made. I am working on a simple site for the company that I work for that allows a customer to input a 5 digit code in and returns what prize they have won. I found some code on a website which done the trick but it doesn't work in Chrome and Safari. My Javascript knowledge is extremely limited but I think I've narrowed it down to the "document.implentation.createDocument" line although the few fixes I've found, I can't get to work. Here is the code I have at the moment before I applied the fixes (this works in FF and IE). Code: <script type="text/javascript"> window.onload = loadIndex; function loadIndex() { // load indexfile // most current browsers support document.implementation if (document.implementation && document.implementation.createDocument) { xmlDoc = document.implementation.createDocument("", "", null); xmlDoc.load("results.xml"); } // MSIE uses ActiveX { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.load("results.xml"); } } function searchIndex() { // search the index (duh!) if (!xmlDoc) { loadIndex(); } // get the search term from a form field with id 'searchme' var searchterm = document.getElementById("searchme").value; var allitems = xmlDoc.getElementsByTagName('item'); results = new Array; if (searchterm.length < 4) { alert("Please re-check and enter your 5 digit code"); } else { for (var i=0;i<allitems.length;i++) { // see if the XML entry matches the search term, // and (if so) store it in an array var name = allitems[i].lastChild.nodeValue; var exp = new RegExp(searchterm,"i"); if ( name.match(exp) != null) { results.push(allitems[i]); } } // send the results to another function that displays them to the user showResults(results, searchterm); } } // Write search results to a table function showResults(results, searchterm) { if (results.length > 0) { // if there are any results, write them to a table document.write('<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Untitled Document</title><link href="cno-competition.css" rel="stylesheet" type="text/css" /></head><body>'); document.write('<div id="container"><div id="logo"></div><div id="prizeContent"><img src="media/new-york.jpg" width="750" height="500" alt="New York" />'); for(var i=0; i<results.length; i++) { document.write('<h1>Congratulations</h1><p>You entered prize code <b><i>'+searchterm+'</i></b> and have won a <span style="font-weight:bold; color:#75ACC1">' + results[i].getAttribute("prize") + '</span>.</p>'); } document.write('<p>To claim your prize please contact the Complete Night Out team on 01908 544445.</p>'); document.write('</div></div></body></html>'); document.close(); } else { // else tell the user no matches were found var notfound = alert('No results found for '+searchterm+'! Please re-check and enter your 5 digit code'); } } </script> The fix I found added the below into the code but I couldn't get it to work using this. Link here. Code: var xmlhttp = new window.XMLHttpRequest(); xmlhttp.open("GET","results.xml",false); xmlhttp.send(null); xmlDoc = xmlhttp.responseXML.documentElement; Any help would be much appreciated. If you would like to see the site live please click here Thank you. Kishan I have a bunch of checkboxes like below that the user can check some or all and click the button and see the values of all the selected checkboxes. How can I do that? Code: <script> function alertValues(){ } </script> <input type="checkbox" class ="normal2" value="131971" name="list[]" > <input type="checkbox" class ="normal2" value="131973" name="list[]" > <input type="checkbox" class ="normal2" value="131975" name="list[]" > <input type="checkbox" class ="normal2" value="131977" name="list[]" > <input type="button" onClick="alertValues()" Here's my HTML: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <title>The Happy Hoppin' Hotel</title> <script src="happyhoppin.js" language="javascript" type="text/javascript"></script> </head> <body> <h1>The Happy Hoppin' Hotel Checkout Page</h1> <h2>Fill out the form below to calculate balance due</h2> <form> Guest ID Number: <input type="text" id="guestID" /> <br /> <br /> Room Type: <select id="roomType"> <option></option> <option>Parlor</option> <option>Single</option> <option>Double</option> </select> <br /> <br /> Length of Stay: <input type="text" id="stayLength" /> <br /> <br /> Number of Drinks: <input type="text" id="drinkNumber" /> <br /> <br /> Number of Towels: <input type="text" id="towelNumber" /> <br /> <br /> Number of Flushes: <input type="text" id="flushNumber" /> <br /> <br /> Bug Complaints?: <br /> <form name="bugComplaintRadio"> <input type="radio" name="bugComplaint" value="No" />No</label> <br /> <input type="radio" name="bugComplaint" value="Yes" />Yes</label> <br /> </form> <br /> Customer Comments: <br /> <textarea name="customerComment" cols="50" rows="5">Enter your comments here...</textarea> <br /> <br /> <input type="button" onclick="calculateBill()" value="Calculate Bill"> </form> </body> </html> Here's my Javascript: Code: const parlorPrice = 80; const singlePrice = 100; const doublePrice = 150; const drinkPrice = 5; const towelPrice = 3; const flushPrice = 1; var guestID = 0; var roomPrice = 0; var stayLength = 0; var drinkNumber = 0; var towelNumber = 0; var flushNumber = 0; var totalDue = 0; var totalCharge = 0; function calculateBill(){ validateForm(); //roomType// if(roomType == "Parlor"){ roomPrice = parlorPrice; } if(roomType == "Single"){ roomPrice = singlePrice; } if(roomType == "Double"){ roomPrice = doublePrice; } //roomType// //drinkCharge// drinkCharge = drinkNumber * drinkPrice; //drinkCharge// //towelCharge// towelCharge = towelNumber * towelPrice; //towelCharge// //flushCharge// flushCharge = flushNumber * flushPrice; //flushCharge// //totalCharge// totalCharge = roomPrice + drinkCharge + towelCharge + flushCharge; //totalCharge// //**bugDiscount**// function getCheckedRadio() { bugValue = ""; bugLength = document.bugComplaintRadio.bugComplaint.length; var bugDiscount = 0; for (x = 0; x < bugLength; x ++) { if (document.bugComplaintRadio.bugComplaint[x].checked) { bugValue = document.bugComplaintRadio.bugComplaint[x].value; } } if (bugValue == "") { alert("You did not choose whether you had a bug complaint or not"); } if (bugValue = "No"){ bugDiscount = 0; } if (bugValue = "Yes"){ bugDiscount = 20; } } //**bugDiscount**// getCheckedRadio(); //totalDue// totalDue = totalCharge + bugDiscount //totalDue// displayBill(); } function validateForm(){ //guestID// guestID = parseInt(document.getElementById("guestID").value); if(isNaN(guestID)){ alert("Guest ID must be a number"); return; } if(guestID <= 0){ alert("Guest ID must be greater than zero"); return; } //guestID// //roomType// roomType = document.getElementById("roomType").value; if(roomType == ""){ alert("Room type must be selected"); return; } //roomType// //stayLength// stayLength = parseInt(document.getElementById("stayLength").value); if(isNaN(stayLength)){ alert("Length of stay must be a number"); return; } if(stayLength <= 0){ alert("Length of stay must be greater than zero"); return; } //stayLength// //drinkNumber// drinkNumber = parseInt(document.getElementById("drinkNumber").value); if(isNaN(drinkNumber)){ alert("Number of drinks must be a number"); return; } if(drinkNumber <= 0){ alert("Number of drinks must be greater than zero"); return; } if(drinkNumber > 25){ alert("Number of drinks has exceeded 25"); return; } //drinkNumber// //towelNumber// towelNumber = parseInt(document.getElementById("towelNumber").value); if(isNaN(towelNumber)){ alert("Number of towels must be a number"); return; } if(towelNumber <= 0){ alert("Number of towels must be greater than zero"); return; } //towelNumber// //flushNumber// flushNumber = parseInt(document.getElementById("flushNumber").value); if(isNaN(flushNumber)){ alert("Number of flushes must be a number"); return; } if(flushNumber <= 0){ alert("Number of flushes must be greater than zero"); return; } //flushNumber// //customerComment// customerComment = document.getElementById("customerComment"); //customerComment// } function displayBill(){ var newPage = "<html><head><title>Billing Summary</title></head>"; newPage += "<body><h1>Happy Hoppin Hotel</h1>"; newPage += "<h2>Guest Billing Statement</h2>"; newPage += "Guest Identification: #" + guestID; newPage += "<br />"; newPage += "Room Type: " + roomType; newPage += "<br />"; newPage += "Room Charge: $" + roomPrice; newPage += "<br />"; newPage += "Length of Stay: " + stayLength + " days"; newPage += "<br />"; newPage += "Drink Charge: $" + drinkCharge; newPage += "<br />"; newPage += "Towel Charge: $" + towelCharge; newPage += "<br />"; newPage += "Flushing Charge: $" + flushCharge; newPage += "<br />"; newPage += "Total Charge: $" + totalCharge; newPage += "<br />"; newPage += "Discount: $" + bugDiscount; newPage += "<br />"; newPage += "Total Due: $" + totalDue; newPage += "<br />"; newPage += "<h3>Come back and visit us again at the Happy Hoppin' Hotel!</h3>"; var z = window.open("","","width=400,height=500"); z.document.write(newPage); z.document.close(); } My question is, I've been spending countless hours trying to: 1. Make two radio buttons indicating "No" and "Yes", 2. Retrieve which selection the user has made, 3. Change the value of "bugDiscount" or the amount of money ($20 or $0) depending on which choice the user made; $0 for No & $20 for Yes. 4. Subtract the value of bugDiscount (0 or 20) from the totalCharge to get TotalDue I know I'm close, but I've tried any number of variations in my code and I still can't seem to get it right. Can anyone help? Hi, What's a good way/ideal data structure to achieve this? The objective of the code/function is to map user-inputted strings into a pair of specific, hard-coded strings. For example, say the user types "firefox" or "ff", or "fx". The output would be the pair ["browser", "mozilla"], for example. I'm currently using a multidimensional array, but it feels inefficient and I'm having trouble mapping an arbitrary number of inputs into 2 outputs. Code: var strings = [ ["input1", "output1a"], ["input2", "output1a"], ["input3", "output1a"], ["input1", "output1b"], ["input2", "output1b"], ["input3", "output1b"] ]; How should I map the elements ["input1", "input2", "input3"] => ["output1a", "output1b"] ? Another method I used previously was a massive switch statement. This fulfills my needs, but I'm not sure about the efficiency (though if I remember correctly, switch statements become more efficient as size grows, since it uses a hash table?). Code: switch (input) { case "ff": case "firefox": case "fx" : case "ffox": return ["browser", "mozilla"]; case "ie": case "internet explorer": return ["browser", "microsoft"]; ... } Hello. I am a neewb, so bare with me. This code is not working correctly for some reason. If I use it in Internet Explorer it will work, but only if you bring up the history in the url tab. You cannot refresh it for whatever reason. so basically it works in Explorer but no refresh. The big problem is Mozilla. I will not work at all. I have all of the cookies set for third party, remember last visit and so on. It will only display the welcome page for first time visitor. Then it will show the subsequent page, however it will not increment the count +1. I am not sure what is going on here, Explorer works, but with no refresh, and Mozilla does not really work at all? Here is my script currently: <script type="text/javascript"> /* <![CDATA[ */ function hitMySite() { var lastDate = new Date(); lastDate.setMonth(lastDate.getMonth()); var dateString = (lastDate.getMonth() + 1) + "/" + lastDate.getDate() + "/" + lastDate.getFullYear(); if (document.cookie != "") { counter = document.cookie.split("=")[1]; counter = parseInt(counter) + 1; date = document.cookie.split(":")[2]; var expireDate = new Date(); expireDate.setMonth(expireDate.getMonth() + 12); document.cookie = "counter=" + counter + ":date:" + dateString + ";expires=" + expireDate.toGMTString(); document.write("<h1>You last visited this page on: " + date + "<br />You have been to this page " + counter + " times.</h1>"); } else { document.write("<h1>Welcome to my Web site! This is your first visit here so be sure to bookmark my page!</h1>"); var counter = 1; var expireDate = new Date(); expireDate.setMonth(expireDate.getMonth() + 12); document.cookie = "counter=" + counter + ":date:" + dateString + ";expires=" + expireDate.toGMTString(); } } /* ]]> */ </script> </head> <body onload="hitMySite()"> </body> </html> Hi im new to working with cookies so would appreaciate a little help I using the w3c tuturial as a template so heres a link so you can see what im trying to do http://www.w3schools.com/JS/js_cookies.asp Code: function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } } function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } function checkCookie(username) { var username=getCookie("username"); if (username!=null && username!="") { document.getElementById("feedback").innerHTML = " last time you scored " + username); setCookie("username",username,365); } else { if (username=null || username="") { setCookie("username",username,365); } } } I kept the variable names the same so you can follow and I don't confuse myself and make things more complected while im trying to debug it. Some extra information. checkcookie is been given a variable it is just a simple number. Im making a questionnaire which is done but I wont the top of the page to tell the user how much they scored last or tell them this is their first time trying it. The variable being passed to check cookie is their score . at the moment when I click the submit button nothing happens. Where it should trigger a score calculating function which should then call the checkcookie function while passing the score it calculated. I would love if someone can point me in the right direction or help me correct it or atleast explain to me whats going wrong. Thanks and a lots of appreciation if anyone can spare the time Hi im kind of new to cookies in Javascript. But after reading a few tutorials on how the work I started to wonder. Is it possible to grab a cookie made by my phpbb forum? I would love to be able to login on my site using my phpbb forum cookies. Anway if this is a bad idea ore won't work for any reason plz let me know. Thanks Hi everyone! Got a quick (cookie) question. I looked on the internet for some cookie scripts (redirect ones), but unfortunately haven't been too lucky with these. What I want to do is the following: When the cookie is not found it goes to my main page, for example: "www.anynamehere.com" On the main page I can select where I want to go - 'Contacts', 'News', 'Forums' and so on. The main page has a drop down list with these options, each option has it's own link. When I click on 'continue' and go to the specific link (ex. www.anynamehere.com/contacts.html) it should remember my selection, so next time I log into www.anynamehere.com it's automatically will take me to contacts.html. I will not see the main page anymore. Now, if from the contacts page I select 'News' and go to www.anynamehere.com/news.html it has to remember that link as well. So if I close my browser and then reopen it, it should take me to www.anyname.com/news.html. I hope that makes sense. If anyone can give me any pointers I would greatly appreciate it. Maybe there is a script like that available online, I just wasn't lucky enough to find one. Thank you in advance! Hey all, I have set up a cookie that redirects the visitor if they have visited the page before. However, I'd like to make some adjustments to it to where if they have cookies turned off, it automatically redirects them to a page that requests them to turn on cookies. Any ideas? Code: <script> num_days = 24; function ged(noDays){ var today = new Date(); var expr = new Date(today.getTime() + noDays*60*60*1000); return expr.toGMTString(); } function readCookie(cookieName){ var start = document.cookie.indexOf(cookieName); if (start == -1){ document.cookie = "seenit=yes; expires=" + ged(num_days); } else { window.location = go_to; } } var go_to = "/index.php?module=article&id=310"; readCookie("seenit"); </script> Hello there, Could someone tell me how a javascript can get a cookie and use it as a parameter like www.mysite.com?search=COOKIEDATA Thanks you (a) Hi, i have a page with two links on it called link1 and link2, when link1 is clicked it creates a cookie called link with the value link1, when link2 is clicked it creates a cookie called link with the value link2. Also when the links are clicked they produce an overlay like light box with the cookie contents echod inside it. That all works fine apart from if i click link1 and then close the overlay and click link2 the overlay still displays "link1" instead of displaying "link2" even tho the cookie has updated correctly. See it live HERE and heres the source code im using: link.php: Code: <html> <head> <style> .black_overlay{ display: none; position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; background-color: black; z-index:1001; -moz-opacity: 0.8; opacity:.80; filter: alpha(opacity=80); } .white_content { display: none; position: absolute; top: 25%; left: 25%; width: 50%; height: 50%; padding: 16px; border: 16px solid orange; background-color: white; z-index:1002; overflow: auto; } </style> <script language="JavaScript"> function lightbox() { document.getElementById('light').style.display='none'; document.getElementById('fade').style.display='none'; <? $link = $_COOKIE["link"]; ?> } function setCookie(c_name,value,expiredays) { var exdate=new Date(); exdate.setDate(exdate.getDate()+expiredays); document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()); document.getElementById('light').style.display='block'; document.getElementById('fade').style.display='block'; } </script> </head> <body> <p><a href = "javascript:void(0)" onclick = setCookie('link','link1',365)>Link 1</a></p> <p><a href = "javascript:void(0)" onclick = setCookie('link','link2',365)>Link 2</a></p> <div id="divCustomerInfo"><?PHP echo $link;?></div> <div id="light" class="white_content"><? include('include_me.php'); ?> <a href = "javascript:void(0)" onclick = lightbox()></a></div> <div id="fade" class="black_overlay"></div> </body> </html> And include_me.php Code: <?PHP $link = $_COOKIE["link"]; echo $link ?> <html> <head> </head> <a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a> </body> </html> |