why is my JavaScript cookie only working on one page? - javascript

I have a JavaScript cookie question. I have used the example for writing and reading a JavaScript cookie from this site: http://www.tutorialspoint.com/javascript/javascript_cookies.htm. The cookie reads and writes just fine to the same page but once I go to another page with a similar form that it should work in - the information in the cookie is gone.
I had originally gotten this to work off my desktop but once I added it to the DEV site we are testing on - it only works on one page. Basically I can set a cookie on one page with a form and then on another page there will be no cookie to read. However I can create another cookie on the second form and it saves just fine. When I go back to page one form - the first cookie I created populates the form fields.
So:
Form 1 page - cookie 1 created
- then go to -
Form 2 page - cookie 1 doesn't exist but I can create cookie 2
- then go to -
Form 1 page - cookie 1 loads into form 1
- then go to -
Form 2 page - cookie 2 loads into form 2
Additional information about the website:
Apache server
PHP 5.4
AngularJS 1.2.26
Webservice
other JavaScript and jQuery files
3rd party scripts
About the only thing I see in the document.cookie when I debug it is a phpsessid. Could this be blocking my cookies from being carried over the form on the other page? These forms are all on the same domain, so...
The desktop version which is the same as the DEV website:
Page 1
<html>
<head>
<script src="tutorialspoint-cookies.js" type="text/javascript"></script>
</head>
<body>
<h1>FORM 1</h1>
<form name="form_000c" id="form_000c" action="">
<label>First Name:</label>
<input type="text" name="First_Name" id="First_Name" /><br />
<label>Last Name:</label>
<input type="text" name="Last_Name" id="Last_Name" /><br />
<label>Email:</label>
<input type="text" name="Email" id="Email" /><br />
<label>Phone Number:</label>
<input type="text" name="Phone" id="Phone" /><br />
<label>Timeline:</label>
<select name="Timeline" id="Timeline">
<option value="time1">Timeline 1</option>
<option value="time2">Timeline 2</option>
<option value="time3">Timeline 3</option>
<option value="time4">Timeline 4</option>
</select><br />
<label>Measurements:</label>
<select name="Measurements" id="Measurements">
<option value="meas1">Measurement 1</option>
<option value="meas2">Measurement 2</option>
<option value="meas3">Measurement 3</option>
<option value="meas4">Measurement 4</option>
</select><br />
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
go to page 2
</body>
</html>
Page 2
<html>
<head>
<script src="tutorialspoint-cookies.js" type="text/javascript"></script>
</head>
<body onLoad="ReadCookie()">
<h1>FORM 2</h1>
<form name="form_000c" id="form_000c" action="">
<label>First Name:</label>
<input type="text" name="First_Name" id="First_Name" /><br />
<label>Last Name:</label>
<input type="text" name="Last_Name" id="Last_Name" /><br />
<label>Email:</label>
<input type="text" name="Email" id="Email" /><br />
<label>Phone Number:</label>
<input type="text" name="Phone" id="Phone" /><br />
<label>Timeline:</label>
<select name="Timeline" id="Timeline">
<option value="time1">Timeline 1</option>
<option value="time2">Timeline 2</option>
<option value="time3">Timeline 3</option>
<option value="time4">Timeline 4</option>
</select><br />
<label>Measurements:</label>
<select name="Measurements" id="Measurements">
<option value="meas1">Measurement 1</option>
<option value="meas2">Measurement 2</option>
<option value="meas3">Measurement 3</option>
<option value="meas4">Measurement 4</option>
</select><br />
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
go to page 1
</body>
</html>
JavaScript cookie
<!--http://www.tutorialspoint.com/javascript/javascript_cookies.htm
function WriteCookie(){
cookievalue1 = escape(document.form_000c.First_Name.value) + ";";
cookievalue2 = escape(document.form_000c.Last_Name.value) + ";";
cookievalue3 = escape(document.form_000c.Email.value) + ";";
cookievalue4 = escape(document.form_000c.Phone.value) + ";";
cookievalue5 = escape(document.form_000c.Timeline.value) + ";";
cookievalue6 = escape(document.form_000c.Measurements.value) + ";";
document.cookie = "First_Name=" + cookievalue1;
document.cookie = "Last_Name=" + cookievalue2;
document.cookie = "Email=" + cookievalue3;
document.cookie = "Phone=" + cookievalue4;
document.cookie = "Timeline=" + cookievalue5;
document.cookie = "Measurements=" + cookievalue6;
alert("Setting Cookies : " + "First_Name=" + cookievalue1 + "Last_Name=" + cookievalue2 + "Email=" + cookievalue3 + "Phone=" + cookievalue4 + "Timeline=" + cookievalue5 + "Measurements=" + cookievalue6 );
}
function ReadCookie(){
var allcookies = document.cookie;
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
// the cookie is leaving a white space in the name so we need to remove it with .trim()
name = name.trim();
value = cookiearray[i].split('=')[1];
document.getElementById(name).value = value;
}
}

When you are setting cookie, it is important to remember that you need to specify path also.
// use path=/ while setting cookie in javascript
document.cookie = "First_Name=" + cookievalue1 + " path=/";
document.cookie = "Last_Name=" + cookievalue2 + " path=/";
document.cookie = "Email=" + cookievalue3 + " path=/";
document.cookie = "Phone=" + cookievalue4 + " path=/";
document.cookie = "Timeline=" + cookievalue5 + " path=/";
document.cookie = "Measurements=" + cookievalue6 + " path=/";

It's an old question, but still pop as a first link, so I would like to share my observation.
Answer above is perfectly fine, but you should not forget to use the delimiter between options.
Cookies have several options, many of them are important and should be
set. The options are listed after key=value, delimited by ;
javascript info
So it should look like this:
document.cookie = "First_Name=" + cookievalue1 + "; path=/";
document.cookie = "Last_Name=" + cookievalue2 + "; path=/";

Related

Entering multiple records on same HTML page

I am creating a JS form where i need 3 inputs from user and after typing the 3 inputs , on clicking 'Add record' button ,it should display them on the same page one after another (line by line) for every button click. With my code, it is writing every new input entry in the same line and not next line. How do i do it ?
My result:
Andrew Arts 2007 Evelyn Computers 2006
Expected result :
Andrew Arts 2007
Evelyn Computers 2006
function doSubmit() {
document.getElementById('f1').innerHTML += document.myform.name.value + " ";
document.getElementById('f1').innerHTML += document.myform.major.value + " ";
document.getElementById('f1').innerHTML += document.myform.year.value + " ";
return false;
}
<body>
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30" type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<p id='f1'></p>
</body>
You use a <br> tag to break the line inside a <p> tag.
You just have to make a small change in your function :
function doSubmit() {
document.getElementById('f1').innerHTML += document.myform.name.value + " ";
document.getElementById('f1').innerHTML += document.myform.major.value + " ";
document.getElementById('f1').innerHTML += document.myform.year.value + " ";
document.getElementById('f1').innerHTML +='<br />'
return false;
}
If you're looking to style your form values , it would be good to append <p>tag for each form value . It will require a small change like below :
function doSubmit() {
document.getElementById('form-value').innerHTML += '<p>'+ document.myform.name.value + " " + document.myform.major.value + " " + document.myform.year.value + " " + "</p>";
return false;
}
Your HTML :
<body>
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30"
type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<div id="form-value">
</div>
I would suggest creating a new p element for every submitted input. You also don't want to store the user input into the innerHTML, because it can lead to cross-site scripting attacks. To prevent this, you can use innerText instead. Here is an example of how you can achieve all that with your code:
function doSubmit() {
const newInputParagraph = document.createElement("p");
newInputParagraph.innerText += document.myform.name.value + " ";
newInputParagraph.innerText += document.myform.major.value + " ";
newInputParagraph.innerText += document.myform.year.value + " ";
document.getElementById("inputs").appendChild(newInputParagraph);
}
And you need to add container for input results (simple div) to your markup, for example like this:
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30" type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<div id="inputs"></div>

JSON Javascript & HTML

I am a grade 11 level computer programmer and encountered some difficulties when trying to complete our JSON assignment. The goal is to save an object to local storage, but my html and js do not do so. Instead, nothing happens at all. All feedback is appreciated.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" language="javascript" src="JDOS.js">
</script>
<title>Announcements Storage</title>
</head>
<body>
<form>
<fieldset>
<legend>Add New Announcement</legend>
Title:<br>
<input required id="title" type="text"><br>
Category:<br>
<input required id="category" type ="text"><br>
Creator:<br>
<input required id="creator" type="text"><br>
Type:
<select required id='type' name="type" >
<option value="Event">Event</option>
<option value="Reminder">Reminder</option>
<option value="General">General</option>
</select><br>
Date and Time:<br>
<input required id="date" type="date"><br>
<input required id="time" type="time"><br>
Sex:<br>
<select required id='sex'>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="All">All</option>
</select><br>
Grade:<br>
<input required id='grade' type='text'><br>
Message:<br>
<textarea required id="message" rows="10" cols="50">Type
announcement here</textarea><br>
<input type="submit" onclick="createAnnouncement()" value="Post">
</fieldset>
</form>
<div id="showAnnouncement"></div>
</body>
</html>
Javascript begins here:
function createAnnouncement() {
var title= document.getElementById('title').value;
var category= document.getElementById('category').value;
var creator= document.getElementById('creator').value;
var type= document.getElementById('type').value;
var datetime= document.getElementById('datetime').value;
var sex= document.getElementById('sex').value;
var grade= document.getElementById('grade').value;
var message= document.getElementById('message').value;
var announcement = {
Title: title,
Category: category,
Creator: creator,
Type: type,
DateTime: datetime,
Sex: sex,
Grade: grade,
Message: message
};
var x = JSON.stringify(announcement);
localStorage.setItem('announcement', x);
}
function showAnnouncement(){
var obj = localStorage.getItem('announcement').value;
var obj2 = JSON.parse (obj);
document.getElementById('showAnnouncement').innerHTML = "title:" + obj2.title
+ "category:" + obj2.category + "creator:" + obj2.creator + "type:" +
obj2.type + "datetime:" + obj2.datetime + "sex:" + obj2.sex + "grade:" +
obj2.grade + "message:" + obj2.message;
}
You have some errors on your logic here.
Since your input is created as type="submit", it will try to do a HTTP POST instead of calling your createAnnouncement() function. You can change it to type="button".
After that, you need to find a way to trigger the showAnnouncement() function, this could be an element such as an <a> or another <button>.

I have a form with the submit button linked to javascript function but nothing is happening when I click the submit button

I'm trying to make a form which when I click the submit button will send the information from the form fields to a javascript function and then show the results to the user. I've made something like this before that's very similar and works fine, but for some reason this isn't doing anything when I click submit. I must have missed something. Here's the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" >
<title>Javascript Form</title>
</head>
<body>
<form id="formID" name="myform" action="" method="get">
Customer Name:
<input type="text" name="names" value="">
<br/>
Street Address:
<input type="text" name="street" value="">
<br/>
City:
<input type="text" name="city" value="">
<br/>
State:
<input type="text" name="state" value="">
<br/>
Zip Code:
<input type="text" name="zip" value="">
<br/>
Beginning Odometer Reading:
<input type="text" name="beginO" value="">
<br/>
Ending Odometer Reading:
<input type="text" name="edinO" value="">
<br/>
Number of Days Car was Used:
<input type="text" name="days" value="">
<br/>
<input type="button" name="button" value="Submit" onClick="car(this.form)">
</form>
<script type="text/javascript">
function car(form) {
var names = form.names.value;
var street = form.street.value;
var city = form.city.value;
var state = form.state.value;
var zip = form.zip.value;
var beginO = form.beginO.value;
var endO = form.endO.value;
var days = form.days.value;
var miles = endO - beginO;
var charge = days * 15 + miles * 0.12;
alert("Miles driven: " + miles + ". Charge: " + charge + ". Name: " + names + ". Address : " + street + " , " + city + " " + state + " " + zip + ". ");
}
</script>
</body>
</html>
It's because you have a JavaScript error at this line:
var endO = form.endO.value;
You have a typo in your form element name:
<input type="text" name="edinO" value="">
form.endO is undefined, so getting value throws an error.

How to remember a form is extended?

I have a multistep form in my project, the first step of which has a javascript extend field function where a user can add additional fields. If the user goes to the next step, the data is of course stored in Session until final submission. However, the extended form will not be remembered. If the user goes back from next step the additional field and its data is not displayed, worse still, if the data in the additional field is invalid, the user won't see it, as the message is displayed underneath the disappeared field (I'm using Cakephp default validation).
Is there a way, like storing the setting in session, to make it stay?
var counter = 0;
function moreFields(val1, val2, val3) {
counter++;
var newField = document.getElementById(val1).cloneNode(true);
newField.id = '';
newField.style.display = 'block';
var newFields = newField.querySelectorAll('[name], [id], [for], [data-display]');
for (var i=0;i<newFields.length;i++) {
var theNames = newFields[i].name
if (theNames)
newFields[i].name = "data[" + val3 + "][" + counter + "][" + theNames + "]";
var theNames2 = newFields[i].id;
if (theNames2)
newFields[i].id = theNames2 + counter;
console.log(newFields[i].id);
var theNames3 = newFields[i].htmlFor;
if (theNames3)
newFields[i].htmlFor = theNames3 + counter;
//console.log(newFields[i].htmlFor);
var theNames4 = newFields[i].dataset.display;
if (theNames4)
newFields[i].dataset.display = theNames4 + counter;
console.log(newFields[i].dataset.display);
}
var insertHere = document.getElementById(val2);
insertHere.parentNode.insertBefore(newField,insertHere);
}
<span id="readroot" style="display: none">
<div class="row">
<div class="col-lg-6">
<div class="form-group required">
<label for="Student1Grade">Grade</label>
<select name="grade" data-display="#display_student_1_grade" class="form-control" id="Student1Grade" required="required">
<option value="">Please Select</option>
<option value="1">Grade 1</option>
<option value="1">Grade 2</option>
</select>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="Student1Gender">Gender</label>
<select name="gender" data-display="#display_student_1_gender" class="form-control" id="Student1Gender">
<option value="1">Male</option>
<option value="2">Female</option>
</select>
</div>
</div>
</div>
<input class="btn btn-default" type="button" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /><br />
</span>
<span id="writeroot"></span>
<input class="btn btn-default" type="button" onclick="moreFields('readroot', 'writeroot', 'Student')" value="Add Field" />
You need to implement either sessionStorage or localStorage for your page.
localStorage - stores data with no expiration date
sessionStorage - stores data for one session (data is lost when the browser tab is closed)
Here I am just posting sample code for your help through which u can do your desire task. You just need to follow the logical concept from below code and implement in your code.
There is a sample also which is only containing id but you can implement it in other way which can full fill your task.
click here

Displaying the results of a Javascript function

I'm trying to get a javascript function to print out, but nothing comes up. Essentially I'm just setting up a basic page of text boxes, radio buttons and checkboxes for users to fill out and the results of those elements will print out to create a basic barebones profile page.
I apologize in advance for any sloppy or obsolete coding, I'm starting out with this stuff (my first semester of classes in web design). I'm assuming I've made a minor error that I'm not catching that's screwing up with the rest of the code, or I'm just plain missing a key line of code.
Here's the code below (Javascript):
`
function validate()
{
dataOut = document.getElementById("profileOut");
var color = document.profileIn.bgcolor.value;
style.backgroundColor = color;
var border = document.profileIn.border.value;
style.border = border;
var name = document.profileIn.name.value;
dataOut.innerHTML = "<h1 id='name'>" name "</p>";
if (document.GetElementById('sportsgames').checked {
dataOut.innerHTML = "<img src='images/sportsgames.jpg' alt='I like sports and games' />";
} else if (document.GetElementById('tvfilm').checked {
dataOut.innerHTML = "<img src='images/tvfilm.jpg' alt='I like tv and film' />";
} else if (document.GetElementById('artlit').checked {
dataOut.innerHTML = "<img src='images/artlit.jpg' alt='I like art and literature' />";
} else {
dataOut.innerHTML = "<img src='images/nothing.jpg' alt='I hate everything' />";
}
var entry1 = document.profileIn.entry1.value;
dataOut.innerHTML = "<p id='para1'>" entry1 "</p>";
document.getElementById("para1").style.color="#0000FF";
var entry2 = document.profileIn.entry2.value;
dataOut.innerHTML = "<p id='para2'>" entry2 "</p>";
document.getElementById("para2").style.color="#FF0000";
var years = document.profileIn.years.value;
dataOut.innerHTML = "<p>I have been practicing this hobby for " + years + " years.</p>";
var music = document.profileIn.music.value;
dataOut.innerHTML = "<p> My favorite music genre is " + music + ".</p>";
var birthday = document.profileIn.birthday.value;
dataOut.innerHTML = "<p>Birthday:" + music + "</p>";
var email = document.profileIn.email.value;
dataOut.innerHTML = "<p> E-Mail:" + music + "</p>";
var website = document.profileIn.website.value;
dataOut.innerHTML = "<p>Website:" + music + "</p>";
document.getElementById('profileOut').innerHTML = profileOut;
}
</script>`
And the HTML code as well:
<body id="profile">
<form id="profileIn" name="profileIn" method="post" onSubmit="return validate()">
<fieldset id ="set1">
<legend>Your Page</legend>
<label for="bgcolor">
<input type="color" id="bgcolor" name="bgcolor" value="#FFFFFF" /> Select a background color<br>
Choose the thickness of the border<br>
<input type="range" id="border" name="border" value="5" min="0" max="10" step="1" /><br>
0 1 2 3 4 5 6 7 8 9 10
</fieldset>
<fieldset id="set2">
<legend>Your Profile</legend>
Enter your name <input type="text" id="name" name="name" /> <br>
Enter your favourite hobby <br>
<input type="radio" id="sportsgames" name="hobby" value="sportsgames">Sports & Games<br>
<input type="radio" id="tvfilm" name="hobby" value="tvfilm">TV & Film<br>
<input type="radio" id="artlit" name="hobby" value="artlit">Art & Literature<br><br>
<label for="entry">What part of that hobby is your favourite?</label><br>
<textarea id="entry1" name="comments1" rows="8" cols="50">Type in here...</textarea><br>
<label for="entry">Which part of that hobby are you best at?</label><br>
<textarea id="entry2" name="comments2" rows="8" cols="50">Type in here...</textarea><br>
How many years have you practiced this hobby? <br>
<input id="years" type="number" name="years" value="0" min="1" max="100" /><br>
What's your favorite genre of music? <br>
<select id="music">
<option value="Rock">Rock<option>
<option value="Pop">Pop<option>
<option value="Country">Country<option>
<option value="R&B">R&B<option>
<option value="Classical">Classical<option>
</select>
</fieldset>
<fieldset id="set3">
<legend>Your Info</legend>
Birthday <input id="birthday" type="date" name="date" /> <br>
Email <input id="email" name="email" type="email" placeholder="example#gmail.com" /> <br>
Website <input id="website" name="website" type="url" placeholder="www.example.com" />
</fieldset>
<fieldset id="set4">
<input class="btn" type="submit" id="btn1" value="Press to Continue" />
<input class="btn" type="reset" id="btn2" value="Press to Clear" />
</fieldset>
</form>
<section id="profileOut"> </section>
Any help's much appreciated, thanks guys!
Lines like below are incorrect. In Javascript, appending should be done with +.
dataOut.innerHTML = "<h1 id='name'>" name "</p>";
should be
dataOut.innerHTML = "<h1 id='name'>" + name + "</p>";
do you get any errors in your console? (F12 in the browser). Also, the return isn't necessary as far as I know:
onSubmit="return validate()">
can just be:
onSubmit="validate()">
Always check your browser console for errors. A cursory glance revealed:
dataOut.innerHTML = "<p id='para1'>" entry1 "</p>";
Missing concatenation operators here.
In general, though, you seem to be repeatedly overwriting dataOut.innerHTML, which - assuming your code were correct - would just result in "Website: blah" and nothing else. Consider creating an element with createElement, adding text to it (createTextNode, appendChild) and then inserting it.
First Error:
dataOut.innerHTML = "<h1 id='name'>"+name+"</p>"; //Missing +
Second to Forth
if (document.GetElementById('sportsgames').checked) //Missing )
Fifth Error:
dataOut.innerHTML = "<p id='para1'>"+entry1+"</p>"; //Missing +
Sixth Error:
dataOut.innerHTML = "<p id='para2'>"+entry2+"</p>"; //Missing +
You forgot to concatenate (+) some of your variables to your strings, like name, entry1, entry2 so on
Always check your Developer Console if some of your JavaScript is not working.

Categories

Resources