Javascript cookie to store radio button arrays - javascript

I have a javascript cookie which sets a default value of NYY (no, yes, yes) when a user enters the site. Bascially i need to be able to change this default value when a user selects from a list of 3 choices (radio or checkbox) from another page and remember his settings.
Here's my code
<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+"; path=/";
}
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 printCookies(w){
cStr = "";
pCOOKIES = new Array();
pCOOKIES = document.cookie.split('; ');
for(bb = 0; bb < pCOOKIES.length; bb++){
NmeVal = new Array();
NmeVal = pCOOKIES[bb].split('=');
if(NmeVal[0]){
cStr += NmeVal[0] + '=' + unescape(NmeVal[1]) + '; ';
}
}
return cStr;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
function setTheDivStyle() {
if(!readCookie('preference')) {
// if cookie not found display the div and create the cookie
document.getElementById("prefBanner").style.display="block";
/*document.getElementById("prefBanner").style.display="block";*/
createCookie('preference', 'NYY', 365); // 365 day
}
else {
// if cookie found hide the div
document.getElementById("prefBanner").style.display="none";
}
}
// print all cookies set for the domain
allCookies = printCookies();
//document.write(allCookies);
alert(allCookies);
</script>
<body onload="setTheDivStyle();" onclick="setTheDivStyle();">
<div id = "prefBanner" class="prefCookie_banner">cookie policy banner - which the users sees if no cookie is set - to change your cookie preference click here</div>
Newpage: where i want to change the default value of the cookie
<FORM NAME="profileForm">
Performance
<input type="radio" value="Y" id="performance" name="performance"><label for="performance"> Yes</label>
<input type="radio" value="N" id="performance" name="performance"><label for="performance"> No</label><br />
Functional
Yes
No
Tracking
<input type="radio" value="Y" id="tracking" name="tracking"><label for="tracking"> Yes</label>
<input type="radio" value="N" id="tracking" name="tracking"><label for="tracking"> No</label><br />
<input type="submit" >
</FORM>

Well this will work but I will not do it that way but looking at the code and the formulated question this is the best answer.
<input type="radio" value="Y" id="trackingY" name="tracking" onclick="createCookie('preference', 'Y', 365);">
<input type="radio" value="N" id="trackingN" name="tracking" onclick="createCookie('preference', 'N', 365);">
There are some horrible mistake in your code sorry to be direct but if you continue like this it's going to be tough to write bigger function.
The HTML is not valid: an ID is a unique identifier this mean that only 1 element can have the same id.
Use the curly brace where they should go
use the var to declare your variable
The split function return an array why declaring a new array on the variable before the split
pCOOKIES = new Array();
pCOOKIES = document.cookie.split('; ');

Related

I tried to make a name stored into a cookie, but it stopped working

I was trying to make a page where we can chat and it will store its user's name to a cookie on the page. I tried it for a couple times, it worked. Then suddenly the cookie part doesn't work anymore. I am hosting the code on replit. What is the problem?
This is my code:
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i < ca.length; i++) {
let 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() {
user = prompt("Please enter your name (your name wont be on the internet, use your real name. this is a school chat):","");
if (user != "" && user != null) {
setCookie("name", user, 30);
let user = getCookie("name");
document.getElementById("name").value = user;
}
else {
checkCookie()
}
}
function checkname() {
let user = getCookie("name");
if (user == "" && user == null) {
checkCookie()
}
else{
document.getElementById("welcome").innerHTML = "Welcome Back " + user;
document.getElementById("name").value = user;
}
}
</script>
</head>
<body onload=checkname()></body>
<p id="welcome"></p>
<form action="https://online-chat-2.red78massive157.repl.co" method="post">
Name: <br><input name="name" type="text" id="name" readonly/><br>
Message: <br><input name="message" type="text" style='height:100px; width:1000px' required/><br>
<input value="Send" type="submit"/>
</form>
<button onclick=checkCookie()>Change name</button>
<br><br>
<iframe src="https://online-chat-2.red78massive157.repl.co/chat" style='height:1000px; width:500px'/>
</html>
I am not really sure whats not working for you but I found that checkCookie function has an issue. You are trying to use variable user before initialization.
Rewrite code as
function checkCookie() {
const user = prompt("Please enter your name (your name wont be on the internet, use your real name. this is a school chat):","");
if (user != "" && user != null) {
setCookie("name", user, 30);
document.getElementById("name").value = getCookie("name");
}
else {
checkCookie()
}
}

Javascript cookie not saving when user input reaches a certain size

I am trying to Save user input from a textarea in a javascript cookie on the unload of a page and then read it back into a textarea when the user returns. The issue that I am having is the cookie is not saving when the user input reaches a certain length. It seems to be working fine with small strings.
Here is the html:
<html>
<head>
<title>Cookie Test</title>
<link rel="stylesheet" type="text/css" href="css/site.css">
</head>
<body class="full" onload="GetCookies()" onunload="WriteCookies()">
<div class="fullscreen-overlay" id="fullscreen_overlay">
<div class="fullscreen-container js-fullscreen-container">
<div class="textarea-wrap">
<textarea name="fullscreen-contents" id="fullscreen-contents"></textarea>
</div>
</div>
</div>
</body>
</html>
Javascript:
function WriteCookies() {
var d = new Date();
var n = document.getElementById('fullscreen-contents').value;
d.setDate(d.getDate() + 1);
document.cookie = "mainCookie = " + n + "; expires = " + d.toGMTString() + "";
}
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 "";
}
function GetCookies() {
document.getElementById('fullscreen-contents').value = getCookie('mainCookie');
}
Any ideas what could be going on? Thanks!
The max size of a cookie is 4093 bytes. Perhaps the long string is just eclipsing that limit. You could consider localStorage or sessionStorage instead
var text = document.getElementById('fullscreen-contents');
function saveText() {
localStorage.savedText = text.value;
console.log("saved");
}
function getText() {
if (localStorage.savedText) {
text.value = localStorage.savedText;
console.log("loaded");
}
}
Edited: Here is a fiddle

Storing the clicked value in radio buttonswith cookies [duplicate]

This question already has answers here:
Keep the selected option saved within js
(4 answers)
Closed 8 years ago.
Hey guys am new to js actually..I have two radio buttons and a save button..The code i have done
<input id="male" type="radio" name="sex" id="male" value="male">Male
<input id="female" type="radio" name="sex" id="female" value="female">Female
<button id="buttons">Save me </button>
<script>
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;
}
var c = document.getElementById('buttons');
c.onclick = function() {
var c = document.getElementById('male');
var m = document.getElementById('female');
if(c.checked == 'true') {
setCookie('samplecookie', c.value, 30 );
} else if(n.checked == 'true') {
setCookie('anothersamplecookie', n.value, 30);
}
}
</script>
What should i need to do.
Suppose i clicked on the female radio button and click the save button the value needs to be stored and the value will remain be checked even the page is refreshed..The above code didnt works for me ..The radio button gets unchecked when the page is refreshed..
I have asked a similar qus here.But it didnt helped me ..I have heard this can be done with localstorage too..But i dont reall know how to.
Hope you guys would help me with the right code and will be really appreciated..
You need to set AND get the cookie.
FIDDLE
function setCookie(name, value, days) { // from http://www.quirksmode.org/js/cookies.html
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;
}
window.onload = function () {
var gender = getCookie('samplecookie');
if (gender) {
if (gender=="male") document.getElementById('male').click(); // or .checked=true;
else if (gender=="female") document.getElementById('female').click();
}
document.getElementById('buttons').onclick = function () {
var m = document.getElementById('male');
var f = document.getElementById('female');
if (m.checked) {
setCookie('samplecookie', m.value, 30);
} else if (f.checked) {
setCookie('samplecookie', f.value, 30);
}
}
}
I don't know if this is something you'd want. But a thing that comes up to mind is the HTML5 Web Storage functionality.With that feature you can store data on the computer of the user.
So whenever a user changes an input field you can create a javascript call that stores the value into the localstorage:
localStorage.setItem(“inputName”, “value”);
Then when you load the page, you see if any of these values are stored and then fill them in.

javaScript code working in a seperate file but not part of a bigger file

I am making a simple Goal-traking completely offline HTML5 app using localStorage.
The problem that I am facing is, that, Retrieving JSON data is working completely fine in a separate file but not when put together as a part of a bigger system.
I would have kept it in a seperate file and would have stopped worrying about it, but I can't do that because of same-origin policy.
Here is the code that's working fine as a seperate file:
<HTML>
<HEAD>
</HEAD>
<BODY>
<script type="text/javascript">
window.onload = function(){
// setup
var goal = "CN";
var date2 = new Date();
var diff = 0;
var active = true;http://jsfiddle.net/#save
var data = '{"goals": [{"goal":"' + goal + '","duedate":"'
+ date2 + '","noofdays":"' + diff + '","active":"'
+ active + '"}]}';
localStorage.setItem("goals",data);
// test
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
for (i=0; i<goalsObj.goals.length; i++) {
if(goal==goalsObj.goals[i].goal) {
document.body.appendChild(document.createTextNode(
"The goal is " + JSON.stringify(goalsObj.goals[i])));
}
}
}
</script>
</BODY>
</HTML>
and now here is the code that is supposed to work, as all of it's different parts are working fine, all the syntax is correct, but still it is giving absolutely no output:
<HTML>
<HEAD>
</HEAD>
<BODY>
<script type="text/javascript">
function save()
{
//Get data from the form
var goal = document.getElementById("goal").value; //Get 'goal' from form
var date2 = document.getElementById("date2").value; //Get 'duedate' from the form
var active = document.getElementById("active").value; //Get 'active' from form
//Calculating the number of days remaining
var date1 = new Date(); //Current Date and Time
var dd = date1.getDate(); //Current Date
var mm = date1.getMonth()+1; //January is 0!
var yyyy = date1.getFullYear(); //Current Year
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} date1 = mm+'/'+dd+'/'+yyyy; //Parsing the date to the required format
var diff = Math.floor(( Date.parse(date2) - Date.parse(date1) ) / 86400000); //Calculate no. of days remaining
if (localStorage.getItem('gcount') === null) {
localStorage.setItem('gcount', "1");
var data = '{"goals":[{"goal":"'+goal+'","duedate":"'+date2+'","noofdays":"'+diff+'","active":"'+active+'"}]}';
localStorage.setItem("goals",data);
//document.getElementById("temp").innerHTML="first";
}
else{
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
var goal = "CN"
var data = { "goal": goal, "duedate": date2, "noofdays": diff, "active": active};
goalsObj.goals.push(data);
localStorage.setItem("goals", JSON.stringify(goalsObj));
}
}
function load(){
/* // setup
var goal = "CN";
var date2 = new Date();
var diff = 0;
var active = true;http://jsfiddle.net/#save
var data = '{"goals": [{"goal":"' + goal + '","duedate":"'
+ date2 + '","noofdays":"' + diff + '","active":"'
+ active + '"}]}';
localStorage.setItem("goals",data); */
// test
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
for (i=0; i<goalsObj.goals.length; i++) {
if(goal==goalsObj.goals[i].goal) {
document.getElementById("duedate").innerHTML=goalsObj.goals[i].duedate;
document.getElementById("noofdays").innerHTML=goalsObj.goals[i].noofdays;
document.getElementById("active").innerHTML=goalsObj.goals[i].active;
// document.body.appendChild(document.createTextNode("The goal is " + JSON.stringify(goalsObj.goals[i])));
}
}
}
</script>
<form name="input" onsubmit="save(); return false;">
<label>Goal: </label> <input type="text" name="goal" id="goal"><br>
<label>Due Date: </label> <input type="date" name="date2" id="date2"></span><br>
<label>Active: </label><br>
<input type="radio" name="active" id="active" value="Future">Future <br>
<input type="radio" name="active" id="active" value="Present">Present <br> <br>
<!-- Submit button to submit the form -->
<input type="submit" value="submit">
</form>
<form name="load" onsubmit="load(); return false;">
<label>Goal: </label> <input type="text" name="goal" id="goal"><br>
<input type="submit" value="submit">
<p id="temp"></p>
<p id="temp1"></p>
<p id="temp2"></p>
<p id="temp3"></p>
<p id="temp4"></p>
<p id="temp5"></p>
<p id="temp6"></p>
<p id="temp7"></p>
<p id="temp8"></p>
<p id="duedate"></p>
<p id="noofdays"></p>
<p id="active"></p>
</BODY>
</HTML>
I am getting the error that object is not a function. I have tried all other similar questions on StackOverflow and nothing worked.
What's wrong? What should I do?
You are using the same id for multiple different elements.
Also, try using IndexedDB instead of localStorage.

Ghost element in javascript

So I've been designing a remember me button using cookies, and I made two functions to do so:
function checkInfo() {
var blah = $("#remem");
alert(blah.id);
var login = $("#nameInput").val();
var pw = $("#pwInput").val();
if (blah.checked) setCookie(login, pw, 5);
if (localStorage[login] == pw) {
$("#loginscreen").css("display", "none");
$("#ques0").css("display", "block");
} else alert("Your info doesn't match, sorry :(");
}
function setCookie(name, value, daysToLive) {
alert(name);
var text = name + "=" + encodeURIComponent(value);
text = text + ";max-age=" + (daysToLive*60*60*24);
document.cookie = text;
alert(text);
}
For some reason blah can't find the #remem element when run in this form:
<form id = "loginscreen">
<p class = "input" style = "display: block; margin: 0 0 30px 0">Now, log in :)</p>
<p class = "input">Login:</p><input id = "nameInput" type = "text" name = "fName" />
<p class = "input">Password:</p><input id = "pwInput" type = "text" name = "password" />
<input type = "button" value = "Submit" onclick = "checkInfo();" />
<p class = "input">Remember me</p><input id = "remem" type = "checkbox" name = "remember" />
</form>
It's weird, because it finds #nameinput and #pwInput right above it. I also just started javascript like a week ago. help!
blah is a jQuery object, not a plain DOM element, and as such, it does not have id or checked properties. Use prop to access them, e.g., blah.prop('id') and blah.prop('checked'). Alternatively, you can get the underlying DOM element from the jQuery object with blah.get(0).
You are not setting localstorage and you accessing it, so it will create error.
You can create two functions like createCookie and readCookie` like that,
function readCookie(name) {
if(typeof(Storage)!=="undefined"){
// window.localStorage is available!
return localStorage.getItem(name);
} else {
createCookie(name,"",-1);
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;
}
}
//Add cookies//
function createCookie(name,value,days) {
if(typeof(Storage)!=="undefined"){
// window.localStorage is available!
localStorage.setItem(name, value);
} else {
// no native support for HTML5 storage :(
// maybe try dojox.storage or a third-party solution
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires=0";//+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
}
// Use this function in your function like,
function checkInfo() {
var blah = $("#remem");
alert(blah.id);
var login = $("#nameInput").val();
var pw = $("#pwInput").val();
if (blah.checked) createCookie(login, pw, 5);
if (readCookie(login) == pw) {
$("#loginscreen").css("display", "none");
$("#ques0").css("display", "block");
} else alert("Your info doesn't match, sorry :(");
}

Categories