get value for a cookie from a bootrap modal with js - javascript

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>

Related

How to write cookies in form input values with javascript?

I have to use simple cookies for my school project. I tried to put form input values in cookies and I want them displayed once I refresh or submit page. Any other use of cookies is welcome but keep it simple. I searched this site through and I couldn't find an answer on my own.
This is my code:
<html>
<head>
<script>
function setCookie()
{
document.cookie=name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
}
function putCookie() {
setCookie("Name", document.myForm.fn.value);
return true;
}
function readCookie(cname) {
var name = cname + "=";
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()
{
var user = getCookie("username");
if (user != "")
{
alert("Welcome again " + user);
}
}
function uradi(){
let x = readCookie('Name');
let target=document.getElementsByName("fn");
if (x) {
target.value=x;
}
}
</script>
</head>
<body onload="uradi()">
<div id="div1"><img class="slika1"src="port.jpg"></div>
<div class="topnav">
<img class="navigacioni" src="experiment.png" alt="Experimet" id="item">
<img class="navigacioni" src="know.png">
<img class="navigacioni" src="shop.png">
</div>
<div class="formasty">
<form name="myForm" id="form">
<p>First name:</p>
<input required name="fn" type="text" id="first_name"placeholder="First name..." value=""/>
<br>
<input type="button" onclick="putCookie()" id="dugme" value="Remember me">
</form>
</div>
</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

Show div only once per user session? [duplicate]

This question already has answers here:
Show welcome div only once per user / browser session
(3 answers)
Closed 6 years ago.
How would it be done with this? I have jQuery if that would help.
<div id="RLAD-wrapper">
<div id="RLAD">
<p>stuff</p>
</div>
</div>
if(localStorage.getItem("iknowyou")) {
document.body.innerHTML = "You were already here";
} else {
document.body.innerHTML = "Oh. A new guest...";
localStorage.setItem("iknowyou", "true");
}
This utilizes localStorage to store a persistent state across sessions.
You could also do it with cookies:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="mydiv" style="display: none;">
this is a div
</div>
<script
src="https://code.jquery.com/jquery-3.1.1.slim.min.js"
integrity="sha256-/SIrNqv8h6QGKDuNoLGA4iret+kyesCkHGzVUUV0shc="
crossorigin="anonymous"></script>
<script>
$(function() {
// Cookies
function setCookie(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 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;
}
// Validate cookie
var myCookie = getCookie("MyCookie");
if (myCookie == null) {
// alert('No cookei');
$('.mydiv').css('display','block');
setCookie("MyCookie", "foo", 7);
}
else {
// alert('yes cookei');
$('.mydiv').css('display','none');
}
});
</script>
</body>
</html>
The code below sets an item in localStorage to Date.now, and checks if it is past 3 days. The setting of the item is in an else statement to prevent the user from getting their time reset every single time they run the website.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Put anything you want here</title>
</head>
<body>
<div id="aDiv">
Div content
</div>
<script>
if(Date.now() - parseInt(localStorage.getItem("pageVisitedTime").getTime(), 10) < 2.592e+8){
document.getElementById("aDiv").style.display = "none";
}
else{
localStorage.setItem("pageVisitedTime", "" + Date.now());
}
</script>
</body>
</html>

Input js validation & storing inputed user data in cookies

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.

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