Storing the clicked value in radio buttonswith cookies [duplicate] - javascript

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.

Related

Keep the value of shopping cart after page reload

I am replicating a grocery store webpage for a course project and would like to know how to keep the values in the shopping cart even after the webpage has been refreshed. Please let me know if I havent provided enough information...
<button type="button" id="subtract" onclick="decrease()">-</button>
<input class="quantity-box" type="text" id="text" value="0">
<button type="button" id="add" onclick="increase()">+</button>
<br>
<button class="add-button" onclick="add(1)"><i class="fa fa-cart-plus"></i>&nbsp ADD TO CART</button>
<div class="cart">
<h3 class="aisle-header">Shopping Cart</h3>
<!-- list of the articles in the cart -->
<ul id="items">
</ul>
<h3 id="total" style="text-align: right;">Total: 0 $</h3>
</div>
/* This script is to add increment and decrement quanity */
function decrease(){
var textBox = document.getElementById("text");
if (textBox.value > 0){
textBox.value--;
localStorage.setItem('quantity', textBox.value);
}
}
function increase(){
var a = 1;
var textBox = document.getElementById("text");
textBox.value++;
localStorage.setItem('quantity', textBox.value);
}
window.onload = function() {
var textBox = document.getElementById("text");
textBox.value = localStorage.getItem('quantity');
}
/* This script is to add quantity to cart */
// Cost of all products in the cart
var total = 0;
// Index
var i = 1;
// List of the amount of every product in the cart
var itemCost = [];
// Add to cart
function add(n){
// Getting all Id of the selected shirt(brand ex: nike, price and quantity)
brand = "name";
priceId = "price";
quantityId = "text";
// Getting details of the selected shirt
// brand
name = document.getElementById(brand).innerHTML;
// price
price = document.getElementById(priceId).innerHTML;
// quantity
quantity = document.getElementById(quantityId).value;
// Creating a li element to add it to ul
var node = document.createElement("LI");
// id of li element
item = "item"+i;
node.setAttribute("id", item)
// cost of the selected shirt
itemCost[i-1] = Number(price) * Number(quantity);
// Updating the index i
i += 1;
// text of the li element
var textnode = document.createTextNode(name+" "+quantity+" x $"+price+" ");
// add the text to li element
node.appendChild(textnode);
// add li element to ul list
document.getElementById("items").appendChild(node);
total += Number(price) * Number(quantity);
// update the total
document.getElementById("total").innerHTML = "Total: " + total.toFixed(2) + " $";
// Add a remove button
document.getElementById(item).innerHTML += '<button class= "deleItem" onclick="deleItem('+"'"+item+"'"+')">X</button>';
// you have to respect the order of: '' and ""
}
// Remove a product from the cart
function deleItem(eId){
document.getElementById(eId).remove();
// slice is string method
// eId (element Id) contain root + number (ex: item4)
// n is the number in eId
n = Number(eId.slice(-1)) - 1;
// remove the cost of the product deleted from the cart
total -= itemCost[n];
// Updating the cost of products in the cart
document.getElementById("total").innerHTML = "Total: " + total.toFixed(2) + " $";
}
Note: I am able to use AJAX, but I am not familiar with this so if it is included in the solution a brief explanation would suffice. HTML/JAVASCRIPT/CSS/AJAX
Cookies are made for what you need to do, you can use them simply like this example with an array of elements:
var cart = ['Apple', 'Pear', 'Banana'];
var json_str = JSON.stringify(cart);
setCookie('myCart', json_str, '30'); //This cookie lasts for 30 days
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
And then you can read the cookie created earlier like this:
var json_str = getCookie('myCart');
var cart = JSON.parse(json_str);
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 "";
}
To see the cookies, simply open Chrome DevTools (F12 key or Inspect), go to the Application tab and on the left you will find a menu with a Cookies item.
Remember that Chrome doesn't allow cookies for local files and consequently to save data locally you should do so:
// Save data value
localStorage.setItem("name", "John");
// Retrieve data value
var name = localStorage.getItem("name");

I'm having trouble reading a cookie in javascript

When there are multiple cookies on my site my javascript code doesn't work. I do not know how to specify the cookie name in javascript because i'm lacking expirience. The cookie is chancing the background color of the atricle.
Does someone know what i am doing wrong?
this is my code.
<div>
<article id="bg">
<h1>Kies een kleur en kijk wat voor cookie er wordt aangemaakt</h1>
<select id="theme" onchange="setColorCookie()">
<option value="Select Color">Kies een kleur</option>
<option value="red">Rood</option>
<option value="orange">Oranje</option>
<option value="yellow">Geel</option>
<option value="green">Groen</option>
<option value="blue">Blauw</option>
<option value="purple">Paars</option>
<option value="pink">Roze</option>
<option value="brown">Bruin</option>
<option value="black">Zwart</option>
<option value="white">Wit</option>
</select>
</article>
<script type="text/javascript">
window.onload = function ()
{
if (document.cookie.length != 0) {
var nameValueArray = document.cookie.split("=");
document.getElementById("theme").value = nameValueArray[1];
document.getElementById("bg").style.backgroundColor = nameValueArray[1];
}
}
function setColorCookie()
{
var selectedValue = document.getElementById("theme").value;
if (selectedValue != "Select Color")
{
document.getElementById("bg").style.backgroundColor = selectedValue;
document.cookie = "color=" + selectedValue + ";expires=Fri, 5 2019 01:00:00 UTC;";
}
}
</script>
</div>
Take a look at w3schools:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
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 checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
Look here: MDN: Document.cookie or here: JavaScript Cookies.
Instead of var nameValueArray = document.cookie.split("=");, you should do const myCookies = document.cookie.split(";");. Because:
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
allCookies = document.cookie;
In the code above allCookies is a string containing a
semicolon-separated list of all cookies (i.e. key=value pairs).
For example:
allCookies = document.cookie; // allCookies <= "cookie1=cow; cookie2 = pig; cookie3= chicken;"
cookiesArray = allCookies.split(';'); // cookiesArray[] <= ["cookie1=cow", "cookie2 = pig", "cookie3= chicken"]
One more suggestion:
Modify your code like this:
<script type="text/javascript">
window.onload = function () {
const allCookies = document.cookie;
const cookiesArray = allCookies.split(';');
alert('allCookies:' + allCookies);
alert('cookiesArray:' + JSON.stringify(cookiesArray));
if (document.cookie.length != 0) {
...
Re-run your program. When "onload()" triggers, you'll see two successive "alert" pop-ups.
This should help better explain what's going on.
Please - PLEASE - post back if you have questions; if there's something you "don't get". This isn't a difficult concept - I definitely want you to understand it.

save option in input select after refresh

I've made a function with javascript that can add an option in input select if it not exist by selecting option other but after refresh the option added disappear I want to keep it after refresh but i don't know how to do it please if anyone can help i'll be very grateful
It's not possible without having any backend that can save your option somewhere and populate your select option list latter from that saved options.
For this you have to populate your select box option from a array or something similar. Then when you add option to your select box using jquery you must update array. After refresh you will get new option appear properly.
You can also use localStorage. When you populate an input, save it. And when you are going to draw the input, check if localStorage have the data, and prepopulate it
You can use a cookie to save the value then re-populate on refresh
Angular
angular.module('ddlChoiceExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Retrieving a cookie
var ddlChoice= $cookies.get('ddlChoice');
// Setting a cookie
$cookies.put('ddlChoice', 'Option1');
}]);
Or in JS
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 setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
here is my function to add option select:
<script type="text/JavaScript"> function AjoutOptionAuSelect(this_select) {
if (this_select.value == "autreVille")
{
var saisie;
var pass = false;
do
{
if (pass) alert("La valeur est incorrecte. Elle ne doit comporter que des lettres.");
saisie = prompt("Entrer la nouvelle valeur :");
if (saisie == null) return false;
pass = true;
}
while (saisie.match(/[^a-z^éèàç]/i) && saisie != "")
this_select.options[this_select.length] = new Option(saisie, saisie, true, true);
for (var i=0; i < this_select.options.length; i++)
{
if (this_select.options[i].value == saisie)
{
this_select.options[i].selected = true;
}
}
} }</script>
and input select:
<?= $this->Form->input('ville',
array(
'label'=> false,
'options' => array('Casablanca'=>'Casablanca','Rabat'=>'Rabat', 'Fès'=>'Fès','Tanger'=>'Tanger','Marrakech'=>'Marrakech',
'Essaouira'=>'Essaouira','autreVille'=> 'autreVille' ),
'class' => 'form-control ',
'id'=>'ville',
'onChange'=> "AjoutOptionAuSelect(this);"
)
); ?>

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 :(");
}

Javascript cookie to store radio button arrays

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('; ');

Categories