Reading & using cookie values with javascript - javascript

Just off the get go I am incredibly new to javascript, apologies for any silly comments or obvious mistakes in advance.
This is what I'm currently working with:
<div id="currency_select">
<form action="/Default.asp?" method="post" name="CurrencyChoice">
<select onchange="this.form.submit()" name="ER_ID">
<option value="3">EUR</option>
<option value="2">GBP</option>
</select>
<script type="text/javascript">
document.forms['CurrencyChoice'].elements['ER_ID'].value = '';
</script>
</form>
</div>
I want the value from the following cookie "ER%5fID" to be read and then inserted in the value=''field above.
To be completely honest I'm at abit of a loss as I'm not sure what the best way is to read the cookie's value and then have its value inserted where I want.
Once again apologies for any newbie mistakes. I'm having to learn javascript on the fly and I had to start a few days ago.
So I have spent a fair amount of time today trying to figure out what I need which I think is this:
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);
}
}
}
However I'm still unsure as to how to have the appropriate result return within the value field?
Thanks in advance for any assistance.

I am sorry I just do not care to rewrite this, the W3Scools tutorial on cookies is quite comprihensive and even gives you fully completed functions for reading and writing cookies.
It's also a good resource for general JS learning so you should definitely check it out.
The code there is as follows:
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
And usage is:
function checkCookie()
{
var username=getCookie("username");
if (username!="")
{
alert("Welcome again " + username);
}
else
{
username = prompt("Please enter your name:","");
if (username!="" && username!=null)
{
setCookie("username",username,365);
}
}
}
But you can read more in W3Scools own website.
EDIT : So here is the promised fully functional sample in your specific case:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<title>Cookie Example</title>
<script type="text/javascript">
//adds the [String].trim() method to the [String] object if missing
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
var cookieName = "ER_ID";
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++){
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function setOptionFromCookie() {
var select = document.getElementById('ER_ID'), index, value = getCookie(cookieName);
index = select.options.length;
while(index--) {
if(select.options[index].value == value) {
break;
}
}
if(index > -1) {
select.selectedIndex = index;
} else {
alert('no such value in selection');
}
}
function setValue() {
var value = document.getElementById('value').value;
setCookie(cookieName, value, 365);
}
</script>
</head>
<body>
The value that will go into the cookie "ER_ID": <input id="value" value="2" />
<br/>
<button onclick="setValue()">Set Cookie</button>
<button onclick="setOptionFromCookie()">Set Option from cookie</button>
<hr />
<div id="currency_select">
<form action="/Default.asp?" method="post" name="CurrencyChoice">
<select onchange="this.form.submit()" id="ER_ID" name="ER_ID">
<option value="1" selected="selected">Select Currency</option>
<option value="3">EUR</option>
<option value="2">GBP</option>
</select>
<script type="text/javascript">
</script>
</form>
</div>
</body>
</html>
Because I do not have such a cookie in my browser I also made a possibility for you to set the cookie. But it should be fairly easy to understand. Simply set the cookie first and then press "Set Option from cookie" to read the cookie and set the option based on the value.

Related

How do I use cookies to create a number that increases on the click of a button and stays the same after multiple website visits (HTML / JS)?

I'm trying to make a basic website that has a text box that will display a counter. The user can click a button to add one to the counter and I'm trying to make it so that the counter can retain its value across multiple distinct visits to the websites. I'm using cookies to solve the retention issue but I'm not sure that's the best solution. As of right now the counter button isn't working at all. I'm very new to HTML and Java. Thank you in advance. Below is my code.
<html>
<head><meta charset="utf-8">
<title></title>
</head>
<body>
<form id="form1" method="post" name="form1">
<p>
<input id="set_Value" name="set_Value" onclick="setValue()" type="button" value="Add 1" />
</p>
<p>
Counter:<label><input id="bbb" name="bbb" type="text" /> </label>
</p>
</form>
<script type="text/javascript">
function getCookie(cname) {
var name = cname + '=';
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return '';
}
function setCookie(cname, value) {
if(document.cookie(cname) == null) {
document.cookie = cname;
}
document.cookie = cname + '=' + value + ';' + ';path=/';
}
function setValue() {
setCookie(Counter, getValue(Counter)+1);
document.getElementById('bbb').value = getValue(Counter);
}
</script>
</body>
</html>

Read cookie value and fill the value to form fields

I'm trying to pre-populate multiple form fields by reading cookie data. The code does not seem to split the cookie data into fields instead it grouped them together. I cant seem to figure it out.
Here is my code:
<html>
<head>
<script language="JavaScript1.2" type="text/javascript">
var today = new Date();
var expiry = new Date(today.getTime() + 30 * 24 * 3600 * 1000); // plus 30 days
function setCookie(name, value){
document.cookie=name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
}
function putCookie(form){
setCookie("FirstName", form[0].FirstName.value);
setCookie("LastName", form[0].LastName.value);
return true;
}
</script>
<script language="JavaScript1.2" type="text/javascript">
function ReadCookie(){
if (document.cookie != ""){
cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
cookie = cookies[i].trim().split("=");
if (cookie[0] == 'FirstName') {
document.TestForm.FirstName.value = cookie[1];
}
if (cookie[0] == 'LastName') {
document.TestForm.LastName.value = cookie[1];
}
}
}
</script>
</head>
<body onload="ReadCookie()">
<form name="TestForm">
<input type="text" value="Enter Your First Name" id="nameBox" name='FirstName'>
<input type="text" value="Enter Your Last Name" id="nameBox" name='LastName'>
<input type="button" value="Go!" id="submit" onclick="putCookie(document.getElementsByTagName('form'));">
</form>
</body>
</html>
If I understand your code correctly then you are setting a cookie with "FirstName=xxxxx; path=....." and then one with "LastName". document.cookie should give you "FirstName=xxxx;LastName=yyyy". I'm not sure if putCookie() works all right with this code. Doublecheck that the cookies are really set.
So you first have to split the cookies by ";", loop through the cookies and then get the values by "=". Here is an example that should work with your code:
function fillIn(){
if (document.cookie != ""){
cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
cookie = cookies[i].trim().split("=");
if (cookie[0] == 'FirstName') {
document.form1.FirstName.value = cookie[1];
}
if (cookie[0] == 'LastName') {
document.form1.LastName.value = cookie[1];
}
}
}
}
I also checked for the name of the cookie because there might be other cookies flying around as well. :-)

setting multiple cookies on page load

I am new to programming and I struggle a lot with cookies in JavaScript, so I have used this tutorial here. I used the 'create cookie function' but I am unsure about how to make a function that puts the cookies back into the text boxes on page load. I have looked at W3 Schools and still have no idea. Any ideas?
Here is the create cookie function I used which creates cookies from 'more than one' textbox.
function createCookie(nCookie){
var expDate = new Date();
expDate.setMonth(expDate.getMonth() + 12);
var cookieVal = document.getElementById(nCookie).value;
document.cookie = nCookie + "=" + cookieVal + ";path=/;expires=" +
expDate.toGMTString();}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<h2>Working Example</h2>
<form name="myForm" method="get" action="JavaScriptCookies.html" onsubmit="return storeValues(this);">
<fieldset>
<label>Field 1</label><span><input type="text" name="field1" value=""></span>
<label>Field 2</label><span><input type="text" name="field2" value=""></span>
<label>Field 3</label><span><input type="text" name="field3" value=""></span>
<label>Field 4</label><span><input type="text" name="field4" value=""></span>
<span>
<input type="submit" value="Set Cookies">
<input type="button" onclick="showCookies();" value="Retrieve Cookies">
</span>
</fieldset>
</form>
<script type="text/javascript">
function storeValues(form)
{
document.cookie = 'field1=' + form.field1.value;
document.cookie = 'field2=' + form.field2.value;
document.cookie = 'field3=' + form.field3.value;
document.cookie = 'field4=' + form.field4.value;
return true;
}
function showCookies() {
for (var i = 1; i <= 4; i++) {
x = document.getElementsByName("field" + i);
x[0].value = getCookie(x[0].name);
}
return true;
}
function getCookie(cname)
{
var name = cname + "=";
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);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
</script>
</body>
</html>
<script type="text/javascript">
if(field1 = getCookie("field1")) document.myForm.field1.value = field1;
if(field2 = getCookie("field2")) document.myForm.field2.value = field2;
if(field3 = getCookie("field3")) document.myForm.field3.value = field3;
if(field4 = getCookie("field4")) document.myForm.field4.value = field4;
</script>
http://www.w3schools.com/js/js_cookies.asp
BTW if in the EU you need to declare cookie usage

Choose city and redirect to url

The url redirection is not working. I need to let users to select a city and go to the url page. What am I doing wrong?
window.location.href = 'http://' + city + '.example.com';
Thank you.
<script type="text/javascript" src="/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
//<![CDATA[
$(function(){
var cityChosen = getCookie('citychosen');
if(cityChosen!=null && cityChosen!=''){
var chosen = $('#choose option[value="'+cityChosen+'"]');
chosen.attr('selected',true);
}
$("#choose").change(function(){
var selected = $("#choose option:selected");
var output = "";
window.location.href = 'http://' + city + '.example.com';
if(selected.val() != 0){
setCookie('citychosen',selected.val(),365);
}
$("#output").removeClass().addClass(selected.val()).html(output);
});
});
function setCookie(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+"; path=/";
}
function getCookie(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 dropCookie(name) {
createCookie(name,"",-1);
}
//]]>
</script>
</head>
<body>
<select id="choose">
<option value="0">Select city</option>
<option value="amsterdam">Amsterdam</option>
<option value="newyork">New York</option>
<option value="london">London</option>
<option value="cardiff">Cardiff</option>
</select>
You seewindow.location.href here in this code is only a property that deals with the Url location. You need to set it to something in order to function.
The window.location.href is as same as var x="something" here.
So use the method window.open() which serves your purpose
window.open(window.location.href);
Note: There might be any mistake in spellings or syntax. i have just explained functionality. You can use varied parameters also. Have a look at this
First try to move window.location.href to the bottom of the $("#choose").change(function() {}); listener. Second, you are referencing a non-existent city variable, rename that to cityChosen.

Cookie returns undefined value in JavaScript

I want to make a cookie to remember a radius that a user can choose. The problem is that the cookie works, but the value of the cookie is undefined. I don't know what I am doing wrong.
The function "opslaan" is linked with a button on the HTML page.
function opslaan()
{
createCookie('radius',document.getElementById("range").value,8);
alert("opgeslagen");
}
function readCookie(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 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 +";path=/";
}
This is the button and the range field where it need to get the value out:
<fieldset class="one-third column">
<label for="">Radius van de kaart (km)</label>
<input type="range"
min="5"
max="20"
value="5"
step="5"
onchange="showValue(this.value)" />
<span id="range">5</span>
<script type="text/javascript">
function showValue(newValue)
{
document.getElementById("range").innerHTML=newValue;
}
</script>
</fieldset>
<script>
alert(readCookie('radius'));
</script>
<div class="one-third column">
<a class="full-width button margin-top25"
href="home.html"
onclick="opslaan()">
Opslaan
</a>
</div>
It seems to be working without the range field and button.
In your case range is a span not an input element, so you need to use innerHTML property to read the contents of that element instead of using value.
use
document.getElementById("range").innerHTML
instead of
document.getElementById("range").value
Ex:
function opslaan()
{
createCookie('radius',document.getElementById("range").innerHTML,8);
}
Demo: Fiddle
document.getElementById("range").value is going to return undefined. Which is your problem here. Try using document.getElementById("range").innerHTML

Categories

Resources