Im trying to get the following started:
I have a dropdown list which should change a script file and reexecute it based on the droplist choice. It also needs to store the selection variable in a cookie, so in a next visit the right script is launched on loading of the page. At any time the dropdown list can be changed (including the cookie) to change the script once more.
I have attempted to write the script, but the script doesn't work. Some help in fixing this script would be appreciated.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<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;
}
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("droplist-keuze");
if (user != "")
{
loadScript("script'+user+'.js", function());
} else
{
loadScript("script.js", function());
}
}
</script>
<script>
function loadJS(v){
var d=document, h=d.getElementsByTagName('head')[0], newScript;
try {h.removeChild(d.getElementById('lib_lang'));} catch (e){}
newScript = d.createElement('script');
newScript.id = 'lib_lang';
newScript.type = 'text/javascript';
newScript.src = 'script'+v+'.js'; // change your path here
h.appendChild(newScript);
setCookie("droplist-keuze", v, 30;
}
</script>
</head>
<body onload="checkCookie()">
<select lang="en" onchange="loadJS(this.value)">
<option selected="selected" disabled="true"> Select</option>
<option value="1">1 </option>
<option value="2">2 </option>
<option value="3">3 </option>
<option value="4">4 </option>
</select>
</body>
</html>
Related
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.
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
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'm trying to implement cookies for my website, i just wanted to redirect users to a splash page and have a "remember me" checkbox there and once they checked off that and pressed enter, they will not see that page anymore.
So using COOKIE Plugin I can set a cookie for users and redirect them to the page, but I wasn't able to implement how to detect the remember me box..
$(function() {
var COOKIE_NAME = 'splash-page-cookie';
$go = $.cookie(COOKIE_NAME);
if ($go == null) {
$.cookie(COOKIE_NAME, 'test', { path: '/', expires: 6 });
window.location = "/splash.php"
}
else {
}
});
Anybody has done like this before? Or anybody have any similar idea to implement this?
Any help would be appreciated.
Solution #1 (With alert boxes): I came up with this but without the COOKIE Plugin. Hopefully you can get some use out of this. Mostly Pure JS with some JQuery to fancy it up a little.
Here is the DEMO.
Here's the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<!-- JQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('#remember').click(function() {
if (this.checked) {
$('#x').text("You're the Best!");
setCookie();
} else {
$('#x').text("Come on, You know you want to!");
}
});
});
function setCookie() {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
addCookie("username", user, 30);
}
}
function addCookie(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;
//window.location.href = "https://www.google.com"; // redirect after the prompt
}
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) != -1) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
window.location.href = "https://www.google.com";
}
}
function goTo() {
window.location.href = "https://www.google.com";
}
</script>
</head>
<body onLoad="checkCookie();">
<h1>Splash Page</h1>
<form>
<input type="checkbox" id="remember"> Remember me
<br>
<input type="button" value="Enter" onClick="goTo();">
</form>
<p><div id='x'></div></p>
</body>
</html>
Solution #2 (NO alert boxes): I came up with this as a second simplified solution by request which is more compatible with mobile (Chrome, etc.). Hopefully you can get some use out of this. Mostly Pure JS with some JQuery to fancy it up a little.
Here is the DEMO.
Here's the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<!-- JQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('#remember').click(function() {
if (this.checked) {
$('#x').text("You're the Best!!!");
addCookie(30);
} else {
$('#x').text("Come on, You know you want to!");
deleteAllCookies();
}
});
});
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
function addCookie(exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = expires;
}
function checkCookie() {
if (document.cookie == false) {
//alert("Welcome New User");
} else if (document.cookie.indexOf("expires") >= 0) {
//alert("Welcome Back");
window.location.href = "https://www.google.com";
}
}
function goTo() {
window.location.href = "https://www.google.com";
}
</script>
</head>
<body onLoad="checkCookie();">
<h1>Splash Page</h1>
<form>
<input type="checkbox" id="remember"> Remember me
<br>
<input type="button" value="Enter" onClick="goTo();">
</form>
<p><div id='x'></div></p>
</body>
</html>
How does one make the current time appear in an alert box? I'm new to programming, so I'm completely lost. I'm coding in html5 or javascript. I've added most of my code here.
Here's my code:
<script>
function startTime(){
var today=Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
}
</script>
<div id="txt"></div>
<h1>What would you like it to say?</h1>
<p>Commmon Requests:</p>
<form action="">
<select name="requests" onchange ="checkIfOther();" id="dropDown1">
<option value="blank"> </option>
<option value="good morning sir">Good Morning Sir</option>
<option value="current time">Current Time</option>
<option value="other">Other</option>
</select>
</form>
</p>
<button onclick="mySubmit()" value>Submit</button>
<div id="other" style="display:none">
<br><br><label>Optional Request: </label><input type="text" id="otherText"/>
</div>
</body>
</html>
<script>
function checkIfOther(){
a=document.getElementById("dropDown1");
if(a.value == "other"){
document.getElementById("other").setAttribute("style","display:inline");
}
else{
document.getElementById("other").setAttribute("style","display:none");
}
}
</script>
<script type="text/javascript">
function mySubmit(){
var x=document.getElementById("dropDown1");
if(x.value == "other"){
alert("You have chosen: " + otherText.value);
}
else if(x.value == "current time"){
alert("The current time is: " + 'txt'.value); //what do I do here?
}
else{
alert("You have chosen: " + x.options[x.selectedIndex].text);
}
}
</script>
Am I doing something wrong?
First, your HTML is completely screwed. Validate it.
As for the code itself, startTime is broken. It needs new Date().
function startTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
return [ h, m, s ].join(':')
}
and to get it into an alert box you can just do:
alert(startTime());
If you want to put it in an element like <div id="txt"></div> you can do:
document.getElementById('txt').innerHTML = startTime();
You can do something like this.
...
else if(x.value == "current time"){
startTime();
alert("The current time is: " + document.getElementById('txt').innerHTML);
...
Make a function getTime that returns the current time string:
function getTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
return h+":"+m+":"+s;
}
Then use that:
…
else if(x.value == "current time"){
alert("The current time is: " + getTime());
}
…
If you still need the startTime function, you can use it there as well:
function startTime() {
document.getElementById('txt').innerHTML = getTime();
}