Printing localStorage elements onto html page - javascript

Basically i'm wanting to capture a user's shopping basket and then print this information on a separate page. The user would be able to click on a button on the basket page which would take them to the new page (Which would have an invoice like structure showcasing their items, costs etc). Currently i have the following script running on the basket page.
jQuery( document ).ready(function($) {
var itemName = document.getElementById('itemName');
if(typeof(Storage)!=="undefined")
{
var me = {name: itemName.textContent};
localStorage.setItem("user",JSON.stringify(me));
}
else
{
// Sorry! No Web Storage support..
}
});
Which is accessing the following bit of html on the cart page
<!--START: itemnamelink--><a id="itemName" href="product.asp?itemid=[ITEM_CATALOGID]">[ITEM_NAME]</a><!--END: itemnamelink-->
On the new page i'm creating where i want the information to be displayed in an invoice like fashion i have the following code.
<script>
jQuery( document ).ready(function($) {
console.log(localStorage.getItem("user"));
var items = JSON.parse(localStorage.getItem("user"));
for(var key in items){
if(items.hasOwnProperty(key)){
document.getElementById("add").innerHTML += "name:" + "<br>" + items[key];
}
}
});
</script>
<div id="add">
</div>
However i'm getting the following being printed which is not ideal. I eventually want a few more elements being printed. I think my problem is i'm printing the whole of the local storage so in my head it's just dumping it all on one line and i need to iterate through the storage and print each element separately.
name:
red chair black chair

You need to use JSON.parse() to the objects you get from the storage.
var json = '{"name":"black chair red chair"}';
obj = JSON.parse(json);
document.getElementById('element').innerHTML = obj.name;
<div id='element'></div>

function writeToLocalStorage(obj) {
return localStorage.setItem("data", JSON.stringify(obj));
}
function getFromLocalStorage() {
return JSON.parse(localStorage.getItem("data"));
}
writeToLocalStorage({ id: "2", cart: "item" });
var data = getFromLocalStorage();
console.log(data.id);
Then access with data.name

Related

Build hyperlink using value in array in javascript

I'd like to display hyperlinks in my page template based on values in an array.
If the page contains a certain value, I'd like to insert the corresponding hyperlink.
From another question, I've managed to cobble together a script that displays a link when a value is found in a string:
<style>
#viewSchoolLink
{display: none;}
</style>
<div id="schoolName">University of Houston</div>
<div id="viewSchoolLink">View on Some Link</div>
<script type="text/javascript">
var div = document.getElementById("schoolName");
var text = div.innerHTML;
if (text.indexOf("University of Houston") >= 0) {
// if so set display to block.
document.getElementById("viewSchoolLink").style.display = "block";
}
</script>
The thing is, I have like 80-90 schools in my list. I suppose I could create 80-90 separate divs with their own unique links, but I imagine there is a much more efficient way to do it. I have an array I've set up as follows:
const schoolLink = {
"University of Houston": "https://www.somelink.com/widget=4379",
"Vanderbilt University" : "https://www.somelink.com/widget=2537",
"University of Dundee": "https://www.somelink.com/widget=2845",
}
Is there a way I can loop through the array to find a match in the key and then insert the value from the array as a hyperlink?
<script type="text/javascript">
var div = document.getElementById("schoolName");
var text = div.innerHTML;
if (text.indexOf("key in array") >= 0) {
// if so display div and use value from the array as hyperlink
}
</script>
Or, since the only part of the link URL that is unique is the widget number, could I set up my array like this:
const schoolLink = {
"University of Houston": 4379,
"Vanderbilt University" : 2537,
"University of Dundee": 2845,
}
and then just build the URL based on the value in the array:
var part = value in array
var link = ''View on Some Link ';
to insert any of the HTML using Javascript we assign in the following manner:
var div = document.getElementById("schoolName")
div.innerHTML = "<a href='https://www.somelink.com/widget=value in array'/>"
if you want to enter the dynamic data in the place of "value in array", then:
div.innerHTML = `<a href="https://www.somelink.com/widget=${variable}"/>`

How can I store multiple values inside one localStorage key?

How can I store localStorage value without losing last value stored on it
I write code to insert row to table contient data from input everytime I click button 'insert new row' but I have issue after fill the table I want use table's data to insert to SQL database table using localStorage and ajax I do it but my problem he give me just data of last row because when I click save he give localStorage new value
<!-- my problem : console.log shows me last item - I want to store all my inputs products without losing previous when I click button save -->
<input type="text" id="products">
<button onclick="myfunction()">save</button>
<script>
function myfunction() {
var products = document.getElementbyid("products").value;
var save_listProducts = localStorage.setItem("data",products);
}
var get_listProducts = localStorage.getItem("data");
console.log(get_listProducts);
</script>
You need to add little bit more code in order to maintain a "list" (array) in localStorage. There is no problem with actually storing an array in localStorage as long as it is a string - and to convert an array into a string ( and be able to parse it back later ) you can use JSON.stringify (and JSON.parse to get it back)
function addNewItem (item) {
let myList = JSON.parse(localStorage.getItem("myList", "[]"));
myList.push(item);
localStorage.setItem("myList", JSON.stringify(myList));
}
function getAllItems () {
return JSON.parse(localStorage.getItem("myList", "[]"));
}
function removeItem (index) {
let myList = JSON.parse(localStorage.getItem("myList", "[]"));
myList.splice(index, 1);
localStorage.setItem("myList", JSON.stringify(myList));
}
👆 This is just an example and would need to be modified to fit your code, please do not just copy/paste it
In your example
<input type="text" id="product">
<button onclick="myfunction()">save</button>
<script>
function myfunction() {
var product = document.getElementbyid("product").value;
addNewItem(product);
console.log(getAllItems());
}
function addNewItem (item) {
var myList = JSON.parse(localStorage.getItem("myList", "[]"));
myList.push(item);
localStorage.setItem("myList", JSON.stringify(myList));
}
function getAllItems () {
return JSON.parse(localStorage.getItem("myList", "[]"));
}
</script>

Array not being filled when the HTML page loads

I am working on a project using Google Apps Script coupled with HTML and JS. I am fairly new to programming, so bear with me if this is a simple question.
Basically, in my JS file I have a function that calls a function contained in the Google Apps Script (from now on, GAS) file using this method; the GAS function populates an array with values retrieved from a Google Sheets and returns the array. This array is then used by the JS file to populate a drop down list in the HTML file.
The issue is that the dropdown list is not populated at all; if I reload the page with the Google Chrome console on, I see that the array is empty; however, if I click on the empty array, the values are shown, as if it is not populated on page load. See the picture below to have a better understanding of what I mean:
Google Chrome Console screenshot
Below you'll find the relevant snippets of code that handle the differente functions:
JS:
$(function() {
var cities = [];
function onSuccess(elem, array) {
var i = 0;
for (item in elem) {
array.push(elem[i])
i++;
};
return array
};
google.script.run.withSuccessHandler(onSuccess).withUserObject(cities).populate();
//Create the dropdown menu for the cities
for (city in cities) {
var element = $("#city1").append("<option value=" + cities[city].toLowerCase() + ">" + cities[city] + "</option>");
console.log(city);
};
[...]
});
HTML:
<select id="city1" name="city" placeholder="City"><option id="citydummy">City</option></select>
Google Apps Script:
function populate() {
var db = SpreadsheetApp.openById('SHEETID');
var check = true;
var array = [];
for (var i = 2; i < db.getLastRow(); i++) {
db.getActiveSheet().getRange(i, "1").getValue()
array.push(db.getActiveSheet().getRange(i, "1").getValue())
}
return array;
}
Many thanks in advance for anyone who will contribute!
How about the following modification for JS? HTML and GAS are not modified. Data obtained at populate() is directly sent to onSuccess(), and imported the data to the list.
JS :
$(function() {
google.script.run.withSuccessHandler(onSuccess).populate();
});
function onSuccess(cities) {
for (city in cities) {
var element = $("#city1").append("<option value=" + cities[city].toLowerCase() + ">" + cities[city] + "</option>");
console.log(city);
};
};
If I misunderstand your situation, I'm sorry.

LocalStorage does not update when I submit details from edit form

I am using jQuery to develop a mobile app. The interesting thing is when I edit the details of an employee, in the listview the update is visible, but when I look in the localstorage the update does not reflect, also the page for full details of the employee does not update as well. However if I refresh the browser the updates show. How do I get both the localstorage and details page to update without refreshing the browser.
I am using two different forms, one to add a new employee, and another to edit employee details.
Thanks for any suggestions
Here are my codes for adding new employee
//user input to Add Employee Form
$('#add_new_employee_form').on('submit', function(){
var newEmployee = {
id: employees.length+1,
employeeno: $('#employeeno').val(),
employeename:$('#employeename').val(),
employeebirth:$('#employeebirth').val(),
employeestate: $('#employeestate').val(),
employeephone:$('#employeephone').val(),
};
employees.push(newEmployee);
addEmployee(newEmployee);
//save offline
localStorage.setItem('employees', JSON.stringify(employees));
//Alert when case saved successfull
toast('Employee added successfully.');
//refresh the list view
$('#employee_list').listview("refresh");
//Change page to home
$.mobile.changePage('#home_page');
return true;
});
//execute function to show cases
showEmployees();
Here is my code for editing employee
// Editing Saved Cases
//User input to Edit form function
$('#edit_employee_form').on("submit", function(){
var x=document.forms["edit_employee_form"]["id"].value; //here we are taking the value of employee id
//and saves the new values to editEmployees
var editEmployees = JSON.stringify({
id: x,
employeeno: document.forms["edit_employee_form"][" employeeno"].value,
employeename:document.forms["edit_employee_form"]["employeename"].value,
employeebirth:document.forms["edit_employee_form"]["employeebirth"].value,
employeestate: document.forms["edit_employee_form"]["employeestate"].value,
employeephone:document.forms["edit_employee_form"]["employeephone"].value,
});
var y=x-1;
cases[y]=JSON.parse(editCases); //here we updates the values
//After the selected case has been edited
localStorage.setItem("employees", JSON.stringify(employees)); //set the update values to localstorage
toast('Employee Updated Successfully');
//refresh the list view
$('#employee_list').listview("refresh");
//update list view
showCases();
$.mobile.changePage('#home_page');
//refresh the list view
$('#employee_list').listview("refresh");
return true;
});
//Edit button
$(".edit_button").live('click', 'tap', function(e){
e.stopPropagation();
$.mobile.changePage("#edit_employee_page"); // the edit_employee_page was brought to front for making
// the edit_employee_form inside the access scope
var employeeId=$(this).attr('id'); // here we are taking the id of the button for that particular employee.
$('#edit_employee_page').ready(function(e) { //this is for initializing the values on ready of the edit_employee_page
for (var i = 0; i < employees.length; i++){
if(employees[i].id == employeeId){
document.forms["edit_employee_form"]["id"].value=employeeId;
document.forms["edit_employee_form"]["employeeno"].value=employees[i].employeeno;
document.forms["edit_employee_form"]["employeename"].value=employees[i].employeename;
document.forms["edit_employee_form"]["employeebirth"].value=employees[i].employeebirth;
document.forms["edit_employee_form"]["employeestate"].value=employees[i].employeestate;
document.forms["edit_employee_form"]["employeephone"].value=employees[i].employeephone;
document.forms["edit_employee_form"]["id"].setAttribute('id',"readonly");
}
}
});
return false;
});
Here is the code for the dynamic list view, and dynamic pages for each list item
//add an eliment to list view
var addEmployees = function(empData){
//HTML content of one list element
var listElementHTML = '<li><a class="employee_list" ui-btn ui-btn-e ui-btn-icon-right ui-icon-carat-r" data-transition="fade" data-split-icon="delete" href="#item'+empData.id+'">'+empData.employeename+'<br> '+empData.birth+'</br></a></li>';
//appending the HTML code to list view
$('#employee_list').append(listElementHTML);
//Dynamically adding HTML Pages
var employeePageHTML = '<div id="item'+empData.id+'" data-role="page" data-theme="b"><div data-theme="a" data-role="header"><h1>'+empData.employeename+'</h1>Home\
Delete</div><div data-role="content">\
<div data-role="collapsible" data-inset="false" data-collapsed="true" data-theme="b"><h3>Case Details</h3><i><strong>Employee No:</i></strong>'+empData.employeeno+'</br><i><p><strong>Employee Name:</i></strong> '+empData.employeename+'</br><i><p><strong>State Of Origine:</i></strong>'+empData.state+'</br><i><p><strong>Employee Phone:</i></strong>'+empData.employeephone+'</br><i><p><strong>Date Of Birth:</i></strong>'+empData.birth+'</div></div>\
<div data-position="fixed" data-theme="a" data-role="footer">Edit</div></div></div>';
You can make an AJAX request in jquery that loads the content asynchronously. Using AJAX allows requests and functions to act without reloading the browser because it connects to the server and back within the method. In your jquery you could do the following:
var data="all the data you want to update with";
$.ajax({
$("body").load(data);
//this would load that string inside the body but you can do whatever
you want in this ajax function.
});

global site variable js

I am new to javascript, i am trying to make a small site with two HTML pages (A and B) and a global js file.
So lets say i have selected certain items in page A, the list-preview on Page A gets updated.
But if i want to see the list in detail i have to go to page B.
Page A and B bith use the same .js file, the selected items are saved in a array.
How do i make sure the selected items still stay in the array, and the array doesn't get flushed when i go from page A to page B ?
what i thought of was ...
var selectedProductsName = new Array();
in OwnJS.js
the adding items to the preview list works.
i'm only struggling to keep the array unflushed when i go to page B from page A.
HTML5 introduces a new thing called localStorage. It's basically some kind of storage that is persistent between all pages of your website as well as between user sessions. It can be accessed as a simple key/value store:
var selectedProductsName = localStorage.getItem("selectedProductsName");
And to set:
localStorage.setItem("selectedProductsName", []);
Here's an article about getting started with localStorage, if you want to be able to do more things like checking browser compatibility for localStorage and watching the storage event, among others.
You could use the HTML5 local storage. It lets you tell the browser to save data on the user's machine. (There's also session storage, valid only for the current session.)
Save (in Apply.html)
IN.API.Profile("me")
.fields(["id", "firstName", "lastName", "pictureUrl","headline","industry","location:(name)","positions:(title)","emailAddress"])
.result(function(result) {
profile = result.values[0];
// save all keys to local storage
for (f in profile) localStorage[f] = fields[f];
// more stuff ...
});
to Retrieve (in personal_Info.html)
// retrieve first name from local storage
var firstName = localStorage["firstName"];
if (firstName !== undefined) {
$("#textfield1").attr(value, firstName);
}
Source Page
The Source Page has an HTML Button with a jQuery Click event handler. When the Button is clicked, the values of the Name TextBox and the Technology DropDownList is set as QueryString Parameter and then the page is redirected to the Destination page (Page2.htm).
<input type="button" id="btnQueryString" value="Send" />
<script type="text/javascript">
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val());
window.location.href = url;
});
});
</script>
Destination Page
On the Destination page (Page2.htm), inside the jQuery Page Load event handler the URL of the page is first checked to determine whether it has some QueryString Parameters being received, this is done by checking the window.location.search property. If it has some QueryString Parameters then loop is executed and each QueryString Key and Value Pair is inserted in an Array and finally the values are displayed on the page using the HTML span.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null && queryString["technology"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Name:</b> " + queryString["name"] + " <b>Technology:</b> " + queryString["technology"];
$("#lblData").html(data);
}
});
</script>

Categories

Resources