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
Related
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>
I have to use simple cookies for my school project. I tried to put form input values in cookies and I want them displayed once I refresh or submit page. Any other use of cookies is welcome but keep it simple. I searched this site through and I couldn't find an answer on my own.
This is my code:
<html>
<head>
<script>
function setCookie()
{
document.cookie=name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
}
function putCookie() {
setCookie("Name", document.myForm.fn.value);
return true;
}
function readCookie(cname) {
var name = cname + "=";
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 checkCookie()
{
var user = getCookie("username");
if (user != "")
{
alert("Welcome again " + user);
}
}
function uradi(){
let x = readCookie('Name');
let target=document.getElementsByName("fn");
if (x) {
target.value=x;
}
}
</script>
</head>
<body onload="uradi()">
<div id="div1"><img class="slika1"src="port.jpg"></div>
<div class="topnav">
<img class="navigacioni" src="experiment.png" alt="Experimet" id="item">
<img class="navigacioni" src="know.png">
<img class="navigacioni" src="shop.png">
</div>
<div class="formasty">
<form name="myForm" id="form">
<p>First name:</p>
<input required name="fn" type="text" id="first_name"placeholder="First name..." value=""/>
<br>
<input type="button" onclick="putCookie()" id="dugme" value="Remember me">
</form>
</div>
</body>
</html>
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. :-)
So I want to have a responsive page that displays cookies. I want the values of the function to display on load of the page within the input value, but I've only been able to display it using an onclick function. here is my code:
<script type="text/javascript">
function readCookie(FullName) {
var name = FullName + "=";
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>
<label>First Name from cookie: <input id="name2" maxlength="25" name="namefield" readonly="readonly" size="20" type="text" /> </label>
<input onclick="document.getElementById('name2').value = readCookie('FullName')" type="submit" value="Get cookie" />
How do I get the function to display the result within the input without using a submit button?
Make a <script> element after that <input> with the content of submit button's onclick attribute:
<script type="text/javascript">
function readCookie(FullName) {
var name = FullName + "=";
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>
<label>First Name from cookie: <input id="name2" maxlength="25" name="namefield" readonly="readonly" size="20" type="text" /> </label>
<script>
document.getElementById('name2').value = readCookie('FullName')
</script>
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.