Input js validation & storing inputed user data in cookies - javascript

If name is entered, newsletter class will disappear and newsletter1 class will appear displaying Thankyou for joining, [Nameofuser]
I have a form to input name and email. When the email is entered in correct format, popup appears Successful and I am trying to save that name in cookie. So when I refresh the page, it will display Thankyou for joining, [Nameofuser]
This is what I have achieved so far: I am not able to save the input name in cookies
http://www.w3schools.com/code/tryit.asp?filename=FAEWXAJJ7VKX
https://jsfiddle.net/sachitmaskey/kav5y1ba/
CSS
<head>
<style>
.newsletter {
margin - bottom: 33 px;
}
.newsletter1 {
z - index: 99999;
margin - top: -250 px;
color: red;
}
</style>
</head>
HTML
<body onload = "checkCookie()">
<div class="newsletter" style="float: left;">
<h3>NEWSLETTER</h3>
Name :<input type="text" name="name"><br>
<form name="myForm" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<br><br><input type="submit" value="Submit">
<p id="demo"></p>
</form>
</div>
<div class="newsletter1" style="float: left;">
<p id="thankyou">
</p><br>
</div>
</body>
</html>
**JAVASCRIPT**
<script>
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var name = document.forms["myForm"]["name"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
} else {
alert("Successful");
// If name is entered,newsletter class will disapper and newsletter1 class will appear displaying "Thankyou"
if (y > 0) {
$('.newsletter1').css('display', 'block');
$('.newsletter').css('display', 'none');
// setting cookie, getting cookie and checking cookie if it exist or not
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 + ";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("name");
if (user != "") {
setCookie("name", user, 30);
document.getElementById("thankyou").innerHTML = "Thankyou for joining...."
}
}
}
}
}
</script>

It's a bit outdated to use cookies and I would use window.localStorage instead.
Much simpler:
localStorage.setItem('name', "John Smith");
console.log(localStorage.getItem('name')); // "John Smith"
localStorage.removeItem('name');
console.log(localStorage.getItem('name')); // null

it is better for you to use cache instead of cookies because there might be some possibilities that the session is made expired by your server which meant every time user visits the page is handled by new session and the old session is destroyed. I recommend you to use browser cache instead.

Related

How do I use cookies to create a number that increases on the click of a button and stays the same after multiple website visits (HTML / JS)?

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>

jQuery cookie expiring every page

Trying to create a cookie policy where when the button is click, it doesn't display for 30 days, however when the button is clicked it shows again if you refresh the page or change page.
code is below:
obviously I've added in jQuery at the bottom of the page
<div class="cookie-message" id="cookie_banner">
<div class="container">
<h3>This site uses cookies</h3>
<br>
<p>We use cookies to ensure the functionality and performance of the website. We also like to use analytics cookies to monitor and analyse the use of our website. If you are happy with this, click ‘Accept and Continue’ below or view our cookie policy for more information.</p>
<button id="close_cookie_banner" class="btn btn-custom btn-animate btn-pink"><i class="icon-owia-kokroko"></i> Accept and continue</button>
</div>
</div>
jQuery(document).ready(function($) {
let COOKIE_NAME = "divine_cookie_policy";
if ((getCookie(COOKIE_NAME) === "ACCEPTED")){
// Cookie has been set -> Don't show banner
} else {
// No cookie has been set -> show cookie banner
openCookieBanner();
}
$('#close_cookie_banner').on("click", function (event) {
event.stopPropagation();
closeCookieBanner();
});
/**
* openCookieBanner()
*
* Opens the cookie banner
*/
function openCookieBanner () {
$('#cookie_banner').css({
display: "block"
});
} // END openCookieBanner()
/**
* closeCookieBanner()
*
* Closes the cookie banner
*/
function closeCookieBanner () {
// Prep the date.
var interval = 30;
var date = new Date();
date.setTime(date.getTime() + (interval*24*60*60*1000));
var expires = "expires="+ date.toUTCString();
document.cookie = COOKIE_NAME + "=" + "ACCEPTED" + ";" + expires + ";";
// Close the banner
$('#cookie_banner').css({
display: "none"
});
} // END openCookieBanner()
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 "";
}
}(jQuery));
not really sure what else to try
any help is appreciated

get value for a cookie from a bootrap modal with js

I'm trying to create a modal that has 2 options: yes or no. When a user selects no I will create a condition if value=no then do not display modal.
The issue is that I cannot accomplish it. If is answer is yes I can manipulate the info, I need to display a modal asking a question, get the users answer and based on this and do something every 15 days.
my code is currently not working properly
<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 + ";path=/";
}
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 checkCookie() {
$('#hewant').on('click', function() {
var valyes = $(this).text();
console.log(valyes);
});
$('#hedont').on('click', function() {
var valno = $(this).text();
console.log(valno);
});
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
$("#myModalcashout").modal();
user = "testing me";
if (user != "" && user != null) {
setCookie("username", user, 15);
}
}
}
</script>
<body onload="checkCookie()">
<div class="modal fade" id="myModalcashout">
<div class="modal-dialog">
<!-- for modal to active manually->
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<p style="text-align:center">test</p>
<p style="text-align:center">question</p>
<p style="text-align:center">for u</p>
<div id="hewant" value="yes"> yes i am </div>
<div id="hedont" value="no"> no i dont</div>
</div>
</div>
</div>
</div>
</body>
I restructured your code for you. For starters you only need 1 listener for both buttons, which can be assigned using class on the buttons in the modal (which I changed from div to button tags.
Note: "Run this code snippet" will not work in this sand boxed environment in regards to cookie manipulation so you will have to test this yourself.
There is now a showModal() function that you will call on load that is responsible for showing your modal and attaching a click listener to both buttons on the modal.
When the user clicks yes or no on the modal we get their answer and pass it to checkCookie() function which does as you ask.
I replaced your create and set cookie functions with ones that are tested and work (also added eraseCookie()) there is a great explanation about all 3 functions Here
showModal();
function showModal() {
// only show modal if cookie for the user is null
var user = readCookie("username");
if (user != null) {
alert("Welcome again " + user);
}
else {
user = "testing me";
$("#myModalcashout").modal();
// add listener on buttons
$('.modalButton').on('click', function() {
$('#myModalcashout').modal().hide();
var answer = $(this).val();
console.log(answer);
// create a cookie with the users answer to the modal
createCookie("username", answer, 15);
});
}
}
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 eraseCookie(name) {
createCookie(name, "", -1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://npmcdn.com/tether#1.2.4/dist/js/tether.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<div class="modal fade" id="myModalcashout">
<div class="modal-dialog">
<!-- for modal to active manually->
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<p style="text-align:center">test</p>
<p style="text-align:center">question</p>
<p style="text-align:center">for u</p>
<button class="modalButton" value="yes"> yes i am </button>
<button class="modalButton" value="no"> no i dont</button>
</div>
</div>
</div>
</div>

Read cookie value and fill the value to form fields

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. :-)

Cookie returns undefined value in JavaScript

I want to make a cookie to remember a radius that a user can choose. The problem is that the cookie works, but the value of the cookie is undefined. I don't know what I am doing wrong.
The function "opslaan" is linked with a button on the HTML page.
function opslaan()
{
createCookie('radius',document.getElementById("range").value,8);
alert("opgeslagen");
}
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 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=/";
}
This is the button and the range field where it need to get the value out:
<fieldset class="one-third column">
<label for="">Radius van de kaart (km)</label>
<input type="range"
min="5"
max="20"
value="5"
step="5"
onchange="showValue(this.value)" />
<span id="range">5</span>
<script type="text/javascript">
function showValue(newValue)
{
document.getElementById("range").innerHTML=newValue;
}
</script>
</fieldset>
<script>
alert(readCookie('radius'));
</script>
<div class="one-third column">
<a class="full-width button margin-top25"
href="home.html"
onclick="opslaan()">
Opslaan
</a>
</div>
It seems to be working without the range field and button.
In your case range is a span not an input element, so you need to use innerHTML property to read the contents of that element instead of using value.
use
document.getElementById("range").innerHTML
instead of
document.getElementById("range").value
Ex:
function opslaan()
{
createCookie('radius',document.getElementById("range").innerHTML,8);
}
Demo: Fiddle
document.getElementById("range").value is going to return undefined. Which is your problem here. Try using document.getElementById("range").innerHTML

Categories

Resources