I asked a question earlier with answers which didn't help, I still haven't been able to figure out where my issue is. Originally I thought it was because I had two IDs named the same but this was not the issue.. The form submits and there are no errors but it does not update the values in localStorage?
Edit: After changing const idx to const i the value at position [2] (or final value) would update for every booking (regardless of index). I thought of maybe changing the i value to below but it gives error i is defined before it is initialised?
bookings.findIndex(booking => bookings[i].fname == fname && bookings[i].lname == lname);
Here's what I have (updated code):
// ~~~ add bookings to localStorage
var bookings = JSON.parse(localStorage.getItem("bookings")) || [];
window.onload = showBooking();
$("#submit").click(function() {
var newBookings = {
fname: $('#fname').val(),
lname: $('#lname').val()
}
bookings.push(newBookings);
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
showBooking();
});
// ~~~ edit bookings in localStorage
$(document).on('click','#edit',function (e) {
e.preventDefault();
var parent_form = $(this.form);
var fname = parent_form.find('.input:eq(0)').val();
var lname = parent_form.find('.input:eq(1)').val();
const i = bookings.findIndex(booking => bookings.fname == fname && bookings.lname == lname);
deleteBooking(i);
bookings.push({
fname,
lname
});
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
// showBooking();
});
// ~~~ display bookings in browser
function showBooking() {
var bookingResult = document.getElementById("result");
var ul = document.createElement("ul");
// var bookingItems = JSON.parse(localStorage.getItem("bookings")) || [];
bookingResult.innerHTML = "";
for (let i = 0; i < bookings.length; i++) {
bookingResult.innerHTML += `<div class="card card-body bg-light m-4">
<h3>${bookings[i].fname + " " + bookings[i].lname}
<button onclick="deleteBooking(${i})" class="btn btn-danger text-light ">Delete</button>
<button onclick="editBooking(${i})" class="btn btn-danger text-light ">Edit</button>
</h3>
</div>`;
}
}
// ~~~ edit bookings in browser
function editBooking(i) {
// $('#regForm').hide();
$('#result').hide();
var currentItem = document.getElementById("currentItem");
var editBooking = document.getElementById("editAppt");
currentItem.innerHTML += `<div class="card card-body bg-light m-4">
<h3>${bookings[i].fname + " " + bookings[i].lname} </h3>
</div>`;
editBooking.innerHTML = `<input type="text" class="input" id="fname_${i}" placeholder="${bookings[i].fname}" name="${bookings[i].fname}" value="${bookings[i].fname}" required>
<input type="text" class="input" id="lname_${i}" placeholder="${bookings[i].lname}" name="${bookings[i].lname}" value="${bookings[i].lname}" required>
<input id="edit" type="submit" value="Edit">`;
}
// ~~~ delete bookings from localStorage
function deleteBooking(i) {
bookings.splice(i, 1);
localStorage.setItem("bookings", JSON.stringify(bookings));
showBooking();
}
My HTML form:
<form id="regForm" name="regForm" action="" class="col-sm-6">
<div class="row">
<input type="text" class="input" id="fname" placeholder="First Name" name="fname" required>
<input type="text" class="input" id="lname"placeholder="Last Name" name="lname" required>
<input id="submit" type="submit" value="Submit">
</div>
</form>
<div id="result" class="row"></div>
<div id="currentItem" class="row"></div>
<div id="editAppt" class="row"></div>
There are several changes you need to consider
You have bookings AND bookingItems
You do some changes (I assume there will be some destination change) but do not save them
You parse the localStorage far too often. Not needed. Only read once and write when modified
You cannot have duplicate IDs so you need to delegate and use class names
Be consistent and use jQuery to create elements and to add events- for example the delete button should be d er legates and remove its closest form element
Here is how to find the booking based on names
const idx = bookings.findIndex(booking => bookings.fname == fname && bookings.lname == lname);
Related
I was not able to get this to display the data entered into my table like I wanted. Keeps saying "Uncaught ReferenceError: createRequest is not defined
at HTMLButtonElement.onclick" however I did! or I thought I did... please help me to see what I did wrong! I tried fixing the error messages but it doesn't seem to help.
thank you
function myRequest(medium, subject, quantity) {
requestMedium = medium;
requestSubject = subject;
requestQuantity = quantity;
}
var requestButton = document.getElementById("createRequest");
if (requestButton.addEventListener) {
requestButton.addEventListener("click", Request, false);
} else if (requestButton.attachEvent) {
requestButton.attachEvent("onclick", Request);
}
function createRequest
{
var requestMedium = document.getElementById(medium).value;
var requestSubject = document.getElementById(subject).value;
var requestQuantity = document.getElementById(quantity).value;
//create new request request, store reference in myRequest
//myRequest= new request(requestMedium, requestSubject, requestQuantity);
var addRequest = new Request(requestMedium, requestSubject, requestQuantity);
//display usere's request on page
createRequestDisplay(addRequest);
}
//display gloval request object on page
function displayRequest() {
document.getElementById("requestDisplay").innerHTML = Request.requestMedium + "<br>" +
Request.requestSubject + "<br>" +
Request.requestQuantity;
}
//display any request object to new document node on page
function createDisplayRequest(request) {
// create new object div element
var fragment = document.createElement("div");
//add newObject class name to div element
var classAttrib = document.createAttribute("class");
classAttrib.value = "newObject";
//set class attibute to div fragment;
fragment.setAttributeNode(classAttrib);
//put request object info inside div
fragment.innerHTML = requestMedium + < "br" > +
requestStubject + < "br" > +
requestSubject;
document.body.appendChild(fragment);
}
<div class="main">
<h1>Order Form for comissions</h1>
<legend>Request Comission</legend>
<label for="medium">Medium</label>
<input id="medium" type="text"><br>
<label for="subject">Subjects</label>
<!-- Grader: HTML error needs fixing...missing a '>'' character -->
<!-- <input id="subject" type="subject"<br> -->
<input id="subject" type="text">
<label for="quantity">quantity</label>
<input id="quantity" type="number"><br>
<button id="requestButton" onclick="createRequest">Submit</button>
</div>
<div id="displayRequest">
</div>
Here is a fixed version
var submitRequestBtn = document.getElementById("submitRequestBtn");
submitRequestBtn.addEventListener("click", submitRequest, false);
function submitRequest() {
const medium = document.getElementById('medium').value;
const subject = document.getElementById('subject').value;
const quantity = document.getElementById('quantity').value;
const request = {medium, subject, quantity};
displayRequest(request);
}
function displayRequest(request){
document.getElementById("requestDisplay").innerHTML =
request.medium + "<br>"
+ request.subject + "<br>"
+ request.quantity
;
}
<div class="main">
<h1>Order Form for comissions</h1>
<legend>Request Comission</legend>
<label for="medium">Medium</label>
<input id="medium" type="text"><br>
<label for="subject">Subjects</label>
<input id="subject" type="text">
<label for="quantity">quantity</label>
<input id="quantity"type="number"><br>
<button id="submitRequestBtn" onclick="submitRequest()">Submit</button>
<br/>
<div id ="requestDisplay"></div>
</div>
I have this HTML form:
<div class="input_fields_wrap">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Items</label>
<div class="col-sm-7">
<input type="text" name="items[]" class="form-control items" id="items">
</div>
<div class="col-sm-2">
<button class="add_field_button btn btn-success btn-sm float-right">Add+</button>
</div>
</div>
</div>
It has Add+ functionality which basically add more field. So If I add more field I have multiple ID of this field like: items, items1, items2, etc..
Now, In my JavaScript validation function, I want to check if this Items field or fields are empty or not.
I can check one field but how can I check multiple fields using JavaScript?
JavaScript validation code for one items field:
var items = document.getElementById("items");
if (items.value == "") {
alert("Item name is reuired");
items.focus();
return false;
}
JavaScript code for Add+ functionality:
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
var form = '<div class="delete-row"><div class="form-group row"><label class="col-sm-3 col-form-label">Items</label><div class="col-sm-7"><input type="text" name="items[]" class="form-control items"></div><div class="col-sm-2">( X )</div></div></div>';
$(wrapper).append('<div>'+form+'</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parents('.delete-row').remove(); x--;
})
Full Validation code:
function validateForm () {
var amount = document.forms["salesform"]["amount"];
var buyer = document.forms["salesform"]["buyer"];
var buyerRegex = /^[a-zA-Z0-9_ ]*$/;
var receipt_id = document.forms["salesform"]["receipt_id"];
var receiptIdRegex = /^[a-zA-Z_ ]*$/;
var items = document.querySelectorAll(".items");
var itemsRegex = /^[a-zA-Z_ ]*$/;
var buyer_email = document.forms["salesform"]["buyer_email"];
var note = document.forms["salesform"]["note"];
var city = document.forms["salesform"]["city"];
var phone = document.forms["salesform"]["phone"];
var entry_by = document.forms["salesform"]["entry_by"];
if (amount.value == "") {
alert("Please enter the amount.");
amount.focus();
return false;
} else if (isNaN(amount.value)) {
alert("Amount should be only numeric value.");
amount.focus();
return false;
}
if (buyer.value == "") {
alert("Buyer name is required");
buyer.focus();
return false;
} else if (!buyerRegex.test(buyer.value)) {
alert("Buyer name only contain letter, number and space.");
buyer.focus();
return false;
} else if (buyer.value.length > 20 ) {
alert("Buyer name must be less than 20 characters long.");
buyer.focus();
return false;
}
if (receipt_id.value == "") {
alert("Receipt Id is reuired");
receipt_id.focus();
return false;
} else if (!receiptIdRegex.test(receipt_id.value)) {
alert("Receipt Id must contain only characters.");
receipt_id.focus();
return false;
}
items.forEach(ele => {
if (ele.value == "") {
alert("Item name is required");
ele.focus();// focuses on that particular input
return false;
}
})
return true;
}
You can try something like this,Query SelectorAll,As forEach returns undefined ,you can try with every
const items = [...document.querySelectorAll("input[type=text]")];
items.every(ele => {
//console.log(ele.value)
if (ele.value == "") {
alert("Item name is reuired");
ele.focus();// focuses on that particular input
return false;
}
})
<div class="input_fields_wrap">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Items</label>
<div class="col-sm-7">
<input type="text" name="items[]" class="form-control" id="items">
</div>
<div class="col-sm-2">
<button class="add_field_button btn btn-success btn-sm float-right">Add+</button>
</div>
</div>
</div>
Here's a version of Shubh's answer but querying by class. It's very important to note that you cannot short circuit forEach in javascript by returning from the function, so I altered this solution to use a for loop. For more information you can read this SO question about it.
let items = document.querySelectorAll(".items")
for (let i = 0; i < items.length; i++) {
if (items[i].value == "") {
alert("Item name is required");
items[i].focus(); // focuses on that particular input
return false;
}
})
<div class="input_fields_wrap">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Items</label>
<div class="col-sm-7">
<input class="items" type="text" name="items[]" class="form-control">
</div>
<div class="col-sm-2">
<button class="add_field_button btn btn-success btn-sm float-right">Add+</button>
</div>
</div>
</div>
I would change the input field to have a class that's called item
Then I would loop all those items.
var items = document.querySelectorAll('.item');
for (var i = 0; i < items.length; i++) {
var item = items[i];
// validate
}
The functionality to increment the id is quite useless in your case. getElementById will give you the first match. In your case, where you want to check several elements it'll be wise to use QuerySelectorAll:
document.querySelectorAll('.form-control').forEach(node => {
if(items.value == "") {
...
}
})
I wanted to find out whether it was possible to use a loop to simplify all this rather than hard-coding the entire structure. For the second part of my Javascript where I tried to store the user inputs into localStorage using a for loop, I'm getting an error where it says
CreateEvent.js:72 Uncaught TypeError: name.push is not a function at createReplace (CreateEvent.js:72) at HTMLButtonElement.onclick (CreateEvent.html:130)
HTML:
<span class="border1">
<input class="forms" type="text" id="title" placeholder="Enter Title!">
<p id="title1"></p>
<input class="forms" type="text" id="brief" placeholder="Enter brief description!">
<p id="brief1"></p>
</span>
<div class="Hovertrees">
<p>Hover over me!</p>
<span class="Hovertrees2">
<input class="hover" type="text" id="hover" placeholder="Enter some fun facts!">
<p id="hover1"></p>
</span>
</div>
<div id="what">
<input class="forms" type="text" id="whattitle" placeholder="What is this event?">
<h2 id="whattitle1"></h2>
<input class="forms" type="text" id="whatdesc" placeholder="Enter brief description!">
<p id="whatdesc1"></p>
</div>
<div id="why">
<input class="forms" type="text" id="whytitle" placeholder="Why is this event important?">
<h2 id="whytitle1"></h2>
<input class="forms" type="text" id="whydesc" placeholder="Description of this event">
<p id="whydesc1"></p>
</div>
<div id="fun">
<input class="forms" type="text" id="funtitle" placeholder="Anything interesting you can add!">
<h3 id="funtitle1"></h3>
<input class="forms" type="text" id="fundesc" placeholder="Description of the interesting info!">
<p id="fundesc1"></p>
</div>
Javascript:
var title;
var brief;
var hover;
var whatTitle;
var whatDesc;
var whyTitle;
var whyDesc;
var funTitle;
var funDesc;
function createReplace() {
title = document.getElementById('title').value;
document.getElementById('title1').innerHTML = title;
document.getElementById('title').className = 'hidden';
document.getElementById('news').innerHTML = title;
brief = document.getElementById('brief').value;
document.getElementById('brief1').innerHTML = brief;
document.getElementById('brief').className = 'hidden';
hover = document.getElementById('hover').value;
document.getElementById('hover1').innerHTML = hover;
document.getElementById('hover').className = 'hidden';
whatTitle = document.getElementById('whattitle').value;
document.getElementById('whattitle1').innerHTML = whatTitle;
document.getElementById('whattitle').className = 'hidden';
whatDesc = document.getElementById('whatdesc').value;
document.getElementById('whatdesc1').innerHTML = whatDesc;
document.getElementById('whatdesc').className = 'hidden';
whyTitle = document.getElementById('whytitle').value;
document.getElementById('whytitle1').innerHTML = whyTitle;
document.getElementById('whytitle').className = 'hidden';
whyDesc = document.getElementById('whydesc').value;
document.getElementById('whydesc1').innerHTML = whyDesc;
document.getElementById('whydesc').className = 'hidden';
funTitle = document.getElementById('funtitle').value;
document.getElementById('funtitle1').innerHTML = funTitle;
document.getElementById('funtitle').className = 'hidden';
funDesc = document.getElementById('fundesc').value;
document.getElementById('fundesc1').innerHTML = funDesc;
document.getElementById('fundesc').className = 'hidden';
document.getElementById("create").className = "hidden";
var varNames = [
'titles',
'brief',
'hover',
'whatTitle',
'whatDesc',
'whyTitle',
'funtitle',
'fundesc'
]
for (var name in varNames) {
var value = window[name]
var obj = {name : value};
if(localStorage.getItem(name) != null) {
var tmp = JSON.parse(localStorage.getItem(name));
for(var i = 0;i<tmp.length;i++) {
name.push(tmp[i]);
}
}
name.push(obj);
localStorage.setItem(name, JSON.stringify(value));
}
}
For the first part, simplifying is not possible since you have different properties for each elements.
For the second part, you are getting error because push is a method for array object.But name is an string object declared in for loop
for (var name in varNames) {
var value = window[name]
var obj = {name : value};
if(localStorage.getItem(name) != null) {
var tmp = JSON.parse(localStorage.getItem(name));
for(var i = 0;i<tmp.length;i++) {
name.push(tmp[i]);
}
}
name.push(obj);
localStorage.setItem(name, JSON.stringify(value));
}
}
You can set item in loop
localStorage.setItem(1,'name1');
localStorage.setItem(2,'name2');
localStorage.setItem(3,'name2');
1 2 and 3 would be key that you want to set and then get according to these keys.
localStorage.key(index)
By passing index in key method it will return you the value of that key.
I have a web page that asks user to enter number of networks. Based on number provided by user, it creates corresponding amount of text input fields. User than enters network addresses in those newly created boxes and when user clicks validate, it pings each networks.
Now, I managed to get the dynamically creation on input fields done but now I am having issue accessing their values. Please see below code and jsfiddle:
HTML:
<div ng-app>
<div ng-controller="Controller">
<div class="form-group" id = "numNetDiv" style="display:block">
<div class="col-sm-3">
<label for="numNetworks">Number of Networks</label>
<input id="numNetworks" ng-model="numNetworks"
ng-change="addNetworkFields()" type="text"
class="form-control" required />
<div class="col-sm-3" id="container" style="margin-left: 50px">
</div>
</div>
</div>
<div class="form-group" id = "checkNetsDiv" style="display:block">
<div>
<button id="checkNets" type="button" class="btn btn-nets"
style="margin-left: 100px"
ng-click="checkNets()">
Validate
</button>
</div>
</div>
<p id="demo"></p>
</div>
</div>
angularjs:
// Add input boxes based on # of networks
function Controller($scope){
$scope.count=0;
$scope.addNetworkFields = function() {
var number = document.getElementById("numNetworks").value;
console.log(number);
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Network" + (i+1) + ": "));
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
// Run ping on each subnet
$scope.checkNets = function() {
console.log('Click!')
var number = document.getElementById("numNetworks").value;
for (i=0;i<number;i++){
//Access each networks and run ping on each one after another
// Call below for each network to perform ping
var ping = $.param({network: $scope.network[i]}); // [i] to access each network? Just an idea
$http({
url: 'https://' + location.hostname + '/ping_network',
method: "POST",
data: ping
})
.then(function(response) {
$scope.pingResult = response.data;
})
}
}
}
https://jsfiddle.net/Lwy378ce/137/
I know POST works and the only issue I am having is access each networks one by one and calling that POST on it. For testing, we can get ride of the whole POST code and replace it with something like console.log(network[i]) and see if console can list all networks.
Thanks
Damon
It would be much simpler if you just used a form and the angular js models. You could create your field with ng-repeat, make the ng-model of these input fields the network address and then use those address for the ping. Addresses that would be easily updated when the form is submitted. Also by using ng-show you can hide that validate button until it's useful.
It's also a lot less code.
angular.module('myApp', [])
.controller('myAppCtrl', function($scope){
$scope.number = 0;
$scope.addNetworkFields = function(value) {
$scope.networks = [];
for(var i = 1; i <= parseInt(value); i++){
var network = {number : i, address: ""}
$scope.networks.push(network)
}
}
$scope.submit = function() {
for(var i = 0; i < $scope.networks.length; i++){
console.log($scope.networks[i].address)
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myAppCtrl as ctrl" ng-cloak layout="column" layout-fill>
<form ng-submit="submit()" class="form-group" id = "numNetDiv" style="display:block">
<div class="col-sm-3">
<label for="numNetworks">Number of Networks</label>
<input id="numNetworks" ng-model="number"
ng-change="addNetworkFields(number)" type="number"
class="form-control" required />
<div class="col-sm-3" id="container" style="margin-left: 50px">
<div ng-repeat="network in networks">
<label>Networks {{network.number}}
<input ng-model="network.address"
type="text" class="form-control" /></label>
</div>
<input ng-show="number > 0" type="submit" value="validate"/>
</div>
</div>
</form>
</body>
Here you go: set id to each input and get it by id later.
// Add input boxes based on # of networks
function Controller($scope) {
$scope.count = 0;
$scope.addNetworkFields = function() {
var number = document.getElementById("numNetworks").value;
console.log(number);
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++) {
container.appendChild(document.createTextNode("Network" + (i + 1) + ": "));
var input = document.createElement("input");
input.type = "text";
input.id = "network" + (i + 1);
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
// Run ping on each subnet
$scope.checkNets = function() {
console.log('Click!')
var number = document.getElementById("numNetworks").value;
for (i = 0; i < number; i++) {
//Access each networks and run ping on each one after another
var network = document.getElementById("network" + (i + 1)).value
// Call below for each network to perform ping
var ping = $.param({
network: $scope.network
});
$http({
url: 'https://' + location.hostname + '/ping_network',
method: "POST",
data: ping
})
.then(function(response) {
$scope.pingResult = response.data;
})
}
}
}
I'm new to S.O and javascript. I am working on a final year project for a e-commerce website and have ran into a dead end on saving data from a form into local storage. My code is below, i really don't see where i have gone wrong. all help is appreciated.
window.onload = function() {
// Check for LocalStorage support.
if (localStorage) {
// Populate the form fields
populateForm();
// Get the form
var form = document.getElementById("franchiseForm");
// Event listener for when the bookings form is submitted.
form.addEventListener("submit", function(e) {
saveData(form);
});
}
}
// Save the form data in LocalStorage.
function saveData() {
//fetch sava(data)
var fran_name = document.getElemenyById("fran_name");
var name = document.getElemenyById("name");
var address1 = document.getElemenyById("address1");
var address2 = document.getElemenyById("address2");
var city = document.getElemenyById("city");
var pcode = document.getElemenyById("pcode");
var phone = document.getElemenyById("phone");
//store the values
localStorage.setItem("fran_name", fran_name.value);
localStorage.setItem("name", name.value);
localStorage.setItem("address1", address1.value);
localStorage.setItem("address2", address2.value);
localStorage.setItem("city", city.value);
localStorage.setItem("pcode", pcode.value);
localStorage.setItem("phone", phone.value);
}
// Attempt to populate the form using data stored in LocalStorage.
function populateForm() {
// Fetch the input elements.
var fran_name = document.getElemenyById("fran_name");
var name = document.getElemenyById("name");
var address1 = document.getElemenyById("address1");
var address2 = document.getElemenyById("address2");
var city = document.getElemenyById("city");
var pcode = document.getElemenyById("pcode");
var phone = document.getElemenyById("phone");
//retrieve saved data and update the values of the form.
if (localStorage.getItem("fran_name") != null) {
name.value = localStorage.getItem("fran_name");
}
if (localStorage.getItem("name") != null) {
phone.value = localStorage.getItem("name");
}
if (localStorage.getItem("address1") != null) {
email.value = localStorage.getItem("address1");
}
if (localStorage.getItem("address2") != null) {
email.value = localStorage.getItem("address12");
}
if (localStorage.getItem("city") != null) {
email.value = localStorage.getItem("city");
}
if (localStorage.getItem("pcode") != null) {
email.value = localStorage.getItem("pcode");
}
if (localStorage.getItem("phone") != null) {
email.value = localStorage.getItem("phone");
}
}
window.onload = function(){
if (localstorage){
//populate the form fields
populateform(form);
}
}
<div id="section">
<form id="franchiseForm" action ="Order_confirmation.php" method="POST">
<div class="field">
<label for="fran_name">Franchise Name</label>
<input type="text" name="franchise_name" id="fran_name" placeholder="e.g One Delivery Leeds" pattern="[a-zA-Z]"
autofocus required tabindex="1">
<br>
<label for="name">Name</label>
<input type="text" name="franc_name" id="name" placeholder="Joe Blogs" required tabindex="2">
<br>
<label for="address"> Address</label>
<input type="text" name="franc_address" id="address1" placeholder="Address Line 1" tanindex="3">
<input type="text" id="address2" placeholder="Address Line 2" tabindex="4">
<input type="text" id="city" placeholder="Town/City" tabindex="5">
<input type="text" id="pcode" placeholder="Postcode" tabindex="6">
<br>
<label for="phone" > Phone Number</label>
<input type="tel" name="franc_phone" id="phone" placeholder="Customer service number" min="10" maxlength="11" pattern="[0-9]{3}[-][0-9]{4}[-][0-9]{4}"
required title="Please provide your customer service number in the following format: 000-0000-0000" tabindex="7">
</div>
<div class="field">
<input type="submit" id="submit" value="submit">
</div>
</form>
The main thing is, check your console for this error:
Uncaught ReferenceError: localstorage is not defined.
Change your code. It is localStorage and not localstorage. That's a capital S.
And a big mistake here. It is getElementById and not getElemenyById:
var fran_name = document.getElemenyById("fran_name");
var name = document.getElemenyById("name");
var address1 = document.getElemenyById("address1");
var address2 = document.getElemenyById("address2");
var city = document.getElemenyById("city");
var pcode = document.getElemenyById("pcode");
var phone = document.getElemenyById("phone");
You have too many mistakes! Elemeny != Element.
Looks like this is stopping your code from executing:
if (localStorage.getItem("address1") != null) {
email.value = localStorage.getItem("address1");
}
if (localStorage.getItem("address2") != null) {
email.value = localStorage.getItem("address12");
}
if (localStorage.getItem("city") != null) {
email.value = localStorage.getItem("city");
}
if (localStorage.getItem("pcode") != null) {
email.value = localStorage.getItem("pcode");
}
if (localStorage.getItem("phone") != null) {
email.value = localStorage.getItem("phone");
}
You don't have a variable named email. And moreover, you are trying to set the value of an undefined element variable email, which doesn't have a property named value, that prevents all your scripts from executing.
First of all, not in your code you use:
document.getElemenyById(...);
localstorage.setItem()
instead of (note the Elemeny vs. Element, s vs. S):
document.getElementById(...);
localStorage.setItem();
As for a full solution:
You can use various local storage to store this data in the browser.
You can do something like this when the page is about to reload:
window.onbeforeunload = function() {
var fran_name = document.getElementById("fran_name");
var name = document.getElementById("name");
// ...
localStorage.setItem("fran_name", fran_name.value);
localStorage.setItem("name", name.value);
// ...
}
localstorage works synchronously so this will work here.
At page load you can check:
window.onload = function() {
var name = localStorage.getItem(name);
if (name !== null) document.getElemenyById("name").value = name;
// ...
}
getItem will return null` if the data does not exist.
Use sessionStorage instead of localStorage if you want to store temporarily - until the browser is closed.
Here's a simplified version of your form, with complete working code. save it as a .html file:
<html>
<head>
<script type="text/javascript">
// For saving data:
window.onbeforeunload = function() {
var name = document.getElementById("name");
// ...
localStorage.setItem("name", name.value);
// ...
}
// For loading data:
window.onload = function() {
var name = localStorage.getItem(name);
if (name !== null) document.getElemenyById("name").value = name;
// ...
}
</script>
<title></title>
</head>
<body>
<div id="section">
<form id="franchiseForm" action="Order_confirmation.php" method="POST">
<div class="field">
<label for="name">Name</label>
<input type="text" name="franc_name" id="name" placeholder="Joe Blogs" required tabindex="2">
<br>
</div>
</form>
</div>
</body>
</html>
If you are able to use JQuery and JQuery Cookie, you can save the data in a cookie:
var frn = $(#fran_name).val();
$.cookie("fran_name", frn);
Then on pageload you get the cookie data and then insert it into the field:
$(document).ready(function(){
var cookie = $.cookie("fran_name");
$('#fran_name').val(cookie);
});