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.
Related
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()
}
}
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);"
)
); ?>
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.
I want to ask the user in my webapp with a drop-down menu which school website they want to open, then save that in a cookie and automatically open that website next time they open the webapp. I'm not good at JS so please explain.
Thank's in advance.
<head>
<script>
<!-- Cookie script -->
</script>
</head>
<body>
<form>
<select id="class">
<option value="Choose">Choose</option>
<option value="flah">School#1</option> <!-- Should redirect to site #1 -->
<option value="june">School#2</option> <!-- Should redirect to site #2 -->
</select>
<button type="submit">Välj</button>
</form>
</body>
Update:
<
form>
<select id="class">
<option value="Choose">Choose</option>
<option value="flah">School#1</option> <!-- Should redirect to site #1 -->
<option value="june">School#2</option> <!-- Should redirect to site #2 -->
</select>
<button type="submit" onclick="setCookie()">Välj</button>
</form>
<script type="text/javascript" language="javascript">
function setCookie(cookiename, cookievalue, cookieexdays) {
var d = new Date();
d.setTime(d.getTime() + (cookieexdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cookiename+ "=" + cookievalue+ "; " + expires;
}
function getCookie(cookiename) {
var name = cookiename+ "=";
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 school = getCookie("SelectedSchool");
if (school!= "") {
//redirect to user to link
alert("Welcome to the " + school);
} else {
user = prompt("Please choose your name:", "");
if (school != "" && school != null) {
setCookie("SelectedSchool", school, 365);
}
}
}
</script>
To create a cookie use:
document.cookie="key=value";
To get the value of the select use (example in jquery):
var val = $("#class").val();
Save that in the cookie.
Now next time the user logs in read the cookie using:
var x = document.cookie;
and redirect him with:
location.href = "link";
good luck
Try this, These are the JavaScript function which you can use to save, get or check cookie
<head>
<script>
<!-- Cookie script -->
</script>
</head>
<body>
<form>
<select id="class">
<option value="Choose">Choose</option>
<option value="flah">School#1</option> <!-- Should redirect to site #1 -->
<option value="june">School#2</option> <!-- Should redirect to site #2 -->
</select>
<button type="submit">Välj</button>
</form>
<script type="text/javascript" language="javascript">
function setCookie(cookiename, cookievalue, cookieexdays) {
var d = new Date();
d.setTime(d.getTime() + (cookieexdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cookiename+ "=" + cookievalue+ "; " + expires;
}
function getCookie(cookiename) {
var name = cookiename+ "=";
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 school = getCookie("SelectedSchool");
if (school!= "") {
//redirect to user to link
alert("Welcome to the " + school);
} else {
user = prompt("Please choose your name:", "");
if (school != "" && school != null) {
setCookie("SelectedSchool", school, 365);
}
}
}
</script>
</body>
I have this javascript switch statement:
function showSideMenu() {
switch (document.forms["culinaryrequest"].culinarytype.selectedIndex) {
case 0:
document.getElementById('case1').style.display="none";
document.getElementById('case2').style.display="none";
document.getElementById('case3').style.display="none";
document.getElementById('case4').style.display="none";
break;
case 1:
document.getElementById('case1').style.display="table-row";
document.getElementById('case2').style.display="none";
document.getElementById('case3').style.display="none";
document.getElementById('case4').style.display="none";
break;
case 2:
document.getElementById('case1').style.display="none";
document.getElementById('case2').style.display="table-row";
document.getElementById('case3').style.display="none";
document.getElementById('case4').style.display="none";
break;
case 3:
document.getElementById('case1').style.display="none";
document.getElementById('case2').style.display="none";
document.getElementById('case3').style.display="table-row";
document.getElementById('case4').style.display="none";
break;
case 4:
document.getElementById('case1').style.display="none";
document.getElementById('case2').style.display="none";
document.getElementById('case3').style.display="none";
document.getElementById('case4').style.display="table";
break;
default:
break;
}
}
When a user chooses one of the options from a dropdown menu, it displays a certain element controlled by the above switch statement. The problem is upon refresh or if the user gets an error and is taken back to the page, the element is hidden again. I want to set a cookie to keep the element showing, but I'm not sure how to add cookies to a switch statement. Can I get an example? Thanks!
You could use a framework to do the job.
<html>
<head>
<title></title>
<style type="text/css">
div.case{
display: none;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<script type="text/javascript">
(function($){
$(document).ready(function(){
// Define cookie key
var cookiekey = "mycookiekey";
// Get cases
var cases = $('div.case').hide();
// Set handler
var handler = $('#culinarytype');
// Show case based on cookie
handler.val($.cookie(cookiekey));
// Define the select function
var selectFromHandler = function(){
selected = handler.val();
// First hide all cases
cases.hide();
// Show only wanted case
if(selected > 0){
$(cases.get(selected - 1)).show();
}
// Set cookie
$.cookie(cookiekey, selected, { expires: 7 });
}
// Based on handler change
handler.change(selectFromHandler);
// Default
selectFromHandler();
});
})(jQuery);
</script>
</head>
<body>
<select id="culinarytype">
<option value="0"></option>
<option value="1">Case 1</option>
<option value="2">Case 2</option>
<option value="3">Case 3</option>
<option value="4">Case 4</option>
</select>
<div class="case">Case 1</div>
<div class="case">Case 2</div>
<div class="case">Case 3</div>
<div class="case">Case 4</div>
</body>
</html>
Probably this may help.
Ex.
Setting the cookie
function SetCookie(cookieName,cookieValue) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
}
getting the cookie value
function ReadCookie(cookieName) {
var theCookie=" "+document.cookie;
var ind=theCookie.indexOf(" "+cookieName+"=");
if (ind==-1) ind=theCookie.indexOf(";"+cookieName+"=");
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(";",ind+1);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+cookieName.length+2,ind1));
}
inside the each case call the method setCookie and get the cookie after refresh
function showSideMenu() {
var choice = document.forms["culinaryrequest"].culinarytype.selectedIndex;
for (var x = 1, y = 4; x < y; x++) {
document.getElementById('case' + x).style.display = (x == choice ? (choice == 4 ? "table" : "table-row") : "none");
}
setCookie("MYAWESOMECOOKIE", choice);
}
function getCookie(c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1 ;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return decodeURIComponent(document.cookie.substring(c_start, c_end));
}
}
return null;
}
function setCookie(c_name, value, expires) {
if (typeof(expires) === "undefined") {
expires = 365;
}
var expiresDate = new Date();
expiresDate.setTime(expiresDate.getTime() + (expires * 24 * 3600 * 1000));
document.cookie = c_name + "=" + encodeURIComponent(value) + ((expires == null) ? "" : "; expires=" + expiresDate.toGMTString());
}
function removeCookie(c_name) {
if (getCookie(c_name)) {
document.cookie = c_name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}