How to write cookies in form input values with javascript? - 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>

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>

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>

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.

I want to display a specific cookie(s) into an input using jquery

So I want to have a responsive page that displays cookies. I want the values of the function to display on load of the page within the input value, but I've only been able to display it using an onclick function. here is my code:
<script type="text/javascript">
function readCookie(FullName) {
var name = FullName + "=";
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 "";
}
</script>
<label>First Name from cookie: <input id="name2" maxlength="25" name="namefield" readonly="readonly" size="20" type="text" /> </label>
<input onclick="document.getElementById('name2').value = readCookie('FullName')" type="submit" value="Get cookie" />
How do I get the function to display the result within the input without using a submit button?
Make a <script> element after that <input> with the content of submit button's onclick attribute:
<script type="text/javascript">
function readCookie(FullName) {
var name = FullName + "=";
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 "";
}
</script>
<label>First Name from cookie: <input id="name2" maxlength="25" name="namefield" readonly="readonly" size="20" type="text" /> </label>
<script>
document.getElementById('name2').value = readCookie('FullName')
</script>

setting multiple cookies on page load

I am new to programming and I struggle a lot with cookies in JavaScript, so I have used this tutorial here. I used the 'create cookie function' but I am unsure about how to make a function that puts the cookies back into the text boxes on page load. I have looked at W3 Schools and still have no idea. Any ideas?
Here is the create cookie function I used which creates cookies from 'more than one' textbox.
function createCookie(nCookie){
var expDate = new Date();
expDate.setMonth(expDate.getMonth() + 12);
var cookieVal = document.getElementById(nCookie).value;
document.cookie = nCookie + "=" + cookieVal + ";path=/;expires=" +
expDate.toGMTString();}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<h2>Working Example</h2>
<form name="myForm" method="get" action="JavaScriptCookies.html" onsubmit="return storeValues(this);">
<fieldset>
<label>Field 1</label><span><input type="text" name="field1" value=""></span>
<label>Field 2</label><span><input type="text" name="field2" value=""></span>
<label>Field 3</label><span><input type="text" name="field3" value=""></span>
<label>Field 4</label><span><input type="text" name="field4" value=""></span>
<span>
<input type="submit" value="Set Cookies">
<input type="button" onclick="showCookies();" value="Retrieve Cookies">
</span>
</fieldset>
</form>
<script type="text/javascript">
function storeValues(form)
{
document.cookie = 'field1=' + form.field1.value;
document.cookie = 'field2=' + form.field2.value;
document.cookie = 'field3=' + form.field3.value;
document.cookie = 'field4=' + form.field4.value;
return true;
}
function showCookies() {
for (var i = 1; i <= 4; i++) {
x = document.getElementsByName("field" + i);
x[0].value = getCookie(x[0].name);
}
return true;
}
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 "";
}
</script>
</body>
</html>
<script type="text/javascript">
if(field1 = getCookie("field1")) document.myForm.field1.value = field1;
if(field2 = getCookie("field2")) document.myForm.field2.value = field2;
if(field3 = getCookie("field3")) document.myForm.field3.value = field3;
if(field4 = getCookie("field4")) document.myForm.field4.value = field4;
</script>
http://www.w3schools.com/js/js_cookies.asp
BTW if in the EU you need to declare cookie usage

Categories

Resources