localstorage and JSON - javascript

I need some help with figuring out how local storage and JSON works.
I have the following html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="Script.js"></script>
</head>
<body>
<form name="test" method="post" action="javascript:storage()">
<input name='surname' id="surname" value='surname'>
<input name='lastname' id="lastname" value='lastname'>
<input type="submit" value="test">
</form>
<div id="tabletest"></div>
</body>
</html>
the following javascript:
function storage(){
var surname = document.getElementById('surname').value;
var lastname = document.getElementById('lastname').value;
var person = {
"surname" : surname,
"lastname" : lastname,
"dateofbirth" : "01-01-1990"
};
person = JSON.stringify(person);
localStorage.setItem('person', person);
var person2 = localStorage.getItem('person');
var persons = JSON.parse(person);
var tabletest = document.getElementById('tabletest');
var person3 = JSON.parse(person2);
tabletest.innerHTML += JSON.stringify(person3);
}
My problems/troubles:
The output I get in tabletest is this:
{ "surname":"surname", "lastname":"lastname", "geboortedatum":"01-01-1990" }
How do I get only the surname and the lastname in the 'tabletest' div?
How do I add a new value with the inputs from the textfields when the submitbutton is clicked (because push doesn't work)?

To get lastname(or I should say any value inside JSON) use
tabletest.innerHTML +="Lastname:"+person3.lastname+" Sirname:"+person3.sirname;
And to add to the JSON use:
person.newName = newName
//or
person["newName"] = newName;

Localstorage works on key-value pairs. Since you are using the same key, 'person', you are simply overwriting previous value. You could use an array of persons which you store using 'person' key but you are responsible for parsing/stringifying the array each time.
var personsStore = [];
function storage() {
var s = localStorage.getItem("person");
if (s) {
personsStore = JSON.parse(s);
}
var person = {...} //after you get properties from dom input
personsStore.push(person);
var stringForm = JSON.stringify(personsStore");
localStorage.setItem("person", stringForm);
var tabletest = document.getElementById('tabletest');
tabletest.innerHtml += stringForm;
}
If you want particular attributes the easiest way to do that is to use a tool like underscore (underscore.org). Appending to 'tabletest' becomes
tabletest.innerHtml += JSON.stringify(_.map(personStore, fucntion(p) {
return _.pick(p, "firstname", ....);
});

Here is a fiddle
Right now, your logic shows you grabbing the value of first and last name, which is, currently: surname and lastname, respectively:
<input name='surname' id="surname" value='surname'>
<input name='lastname' id="lastname" value='lastname'>
You need to run this function on the button click event and get the value and simply use the storage setItem(key,value) function. Here is the documentation . You only need to stringify, then parse on the storage data. After that, it is an object that you can get the properties from.
person = JSON.stringify(person);
localStorage.setItem('person', person);
var person2 = localStorage.getItem('person');
var persons = JSON.parse(person2);
var tabletest = document.getElementById('tabletest');
tabletest.innerHTML += persons.surname + ' ' + persons.lastname;
You were very close on the logic, but you needed something like this:
document.getElementById('btnTest').onclick = storage;
I also modified the 'submit' button to a standard 'button' element so that the form doesn't post:
<button id='btnTest' value="test">Test</button>
You could then do Ajax. Otherwise, you would need to do a pre-submit function

Related

How can i get the data from localstorage and view in table using javascript and make a dropdown to sort the table

I have the following code that need to display the id,name and occupation. i can add to local storage but need to display it in table and sort based on name, id and occupation. any idea how can i do it using javascript. sample outputoutput
<!DOCTYPE html>
<html>
<title>Sorting Test</title>
<body>
<fieldset>
<legend>Add participant<legend>
<input id="userID" type="text">
<input id="userName" type="text">
<input id="userOccupation" type="text">
<button id="addbtn" type="button" >Add</button>
</fieldset>
<br>
<div id="displayOutput">
</div>
</body>
<script>
// get the userid, userName and UserOccupation
const userID = document.getElementById("userID");
const userName = document.getElementById("userName");
const userOccupation = document.getElementById("userOccupation");
const addbtn = document.getElementById("addbtn");
const displayOutput = document.getElementById("displayOutput");
//add user input to storage
addbtn.onclick = function(){
const id = userID.value;
const name = userName.value;
const occupation = userOccupation.value;
if(id && name && occupation)
{
let myObj = {
id,
name,
occupation
};
let myObj_serialized = JSON.stringify(myObj);
localStorage.setItem("myObj",myObj_serialized);
}
//view the stored information
for (let i=0; i < localStorage.length; i++)
{
const key = localStorage.key(i);
const value =localStorage.getItem(key);
var row = `<tr><td>${key}: ${value}<td><tr><br/>`;
displayOutput.innerHTML += row;
console.log(value);
}
};
</script>
</html>
You are overriding the stored item values everytime you call setItem. If you want to display a table, I suggest storing an array of objects. If you want to use local storage, Stringify the array before storing and parse it when you need to read it
var storeData = function(data) {
localStorage.setItem("tableData",JSON.stringify(data);
}
storeData([]);
var getData = function() {
return JSON.parse(localStorage.getItem("tableData"));
}
And call something like this to save data:
storeData(getData().push({id: id, name: name, occupation: occupation});
And then to display the data you can do:
var arr = getData();
arr.forEach(element) {
displayOutput.innerHtml += `
<tr>
<td>ID: ${element.id}</td>
<td>Name: ${element.name}</td>
<td>Occupation: ${element.occupation}</td>
</tr>`;
}
As for the sorting, you can call a sort function on the array on the onclick of the table's column header.

Adding new element into a new object and then print out the new object in JavaScript

strong text
Hi all I am a newbie in JavaScript, i am stuck with this problem hopefully anyone can help out thank you . I am trying to create an Application where allow the user to input what kind of food , price that the customer have consume in a restaurant. First the User is required to key in the name of the User . Then when he or she click the" input name" button a new user object is created. I have created a constructor call UserCustomer(). when a new object is created , it will create element inside such as the customer name, price, and a remove user button, if the user want to remove the customer from the list.
After the User click the input name button.the user will be navigate to the Add food page. The user is required to input the food and price which the customer consume,the user can add as many as he wants, when the user click the add Food Button , the program will push the food and price enter into the new customer object created previously.
When the User Click the "done adding". the program will push all value into the array "newMakanUser".
And then finally the function will print loop through this "newMakanUser" and print out the Value
The Result i get is
0: [object Object] 1: [object Object]
The Result that i want to get is
For Example
John Food :Burger Fries cola Price :2.4,1.5,1.0
Linda Food : salad Fruits juice Price : 3.5, 1.0,1,6
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
//This is a New Array
var newMakanUser = [];
var newButton = [];
var placeHolder = [];
var TempVar=[];
var TempUSer= "";
function UserCustomer(nameU){
this.nameUser = nameU;
this.Food = [];
this.Price= [];
var button = document.createElement("button");
button.innerHTML = "Remove " +nameU +" from list ";
// 2. Append somewhere
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
}
function outArray() {
newMakanUser.toString();
newButton.toString();
function displayArrayObjects(arrayObjects,outputName) {
// First Check the Array Length
var len = arrayObjects.length, text = "";
this.outputName = outputName;
//Loop through the Array
for (var i = 0; i < len; i++) {
var myObject = arrayObjects[i];
//Loop through the object in side the array
for (var x in myObject) {
text += ( x + ": " + myObject[x] + " ");
}
text += "<br/>";
}
document.getElementById(outputName).innerHTML = text;
}
displayArrayObjects( newMakanUser,"outputArray");
}
// This Function is to create an object and store it inside an array.
function addName(UserName){
// Get the User Input Object product name
UserName = document.getElementById("NamePax").value;
TempUSer = UserName ;
TempVar.push(new UserCustomer(UserName));
// alert( "Hello");
// newMakanUser.push(new myUserName(createProduct,productprice));
slides.style.display = "block";
slidess.style.display = "none";
slidesss.style.display = "none";
}
function addFoodPrice(Foody,Pricey){
Foody = document.getElementById("FoodyName").value;
Pricey = document.getElementById("FoodyPrice").value;
TempVar.Food.push(Foody);
TempVar.Price.push(Pricey);
}
function doneAdd(){
newMakanUser.push(TempVar);
slides.style.display = "none";
slidess.style.display = "block";
slidesss.style.display = "block";
// document.getElementById("outputDB").innerHTML = text;
}
// This Function will remove the unwanted object
</script>
</head>
<body>
<h2>Who Order the Food</h2>
<P> <input type="button" value="Check what you order" id="" onclick="outArray();"/></P>
<p id="outputArray"></p>
<p id="outputDB"></p>
<div id="slidesss" style="display:block">
<P style="color:blue;"><strong>Person Name:</strong><input type="text" style="text-align:center; margin-left:10px;"id="NamePax" name="element"
placeholder="Person Name" ></P>
</div>
<div id="slides" style="display:none"> <!-- set display to none -->
<P style="color:blue;"><strong>Food Name :</strong><input type="text" style="text-align:center; margin-left:10px;"id="FoodyName" name="element"
placeholder="Food Name" ></P>
<P style="color:blue;"><strong>Food Price :</strong><input type="text" style="text-align:center; margin-left:10px;"id="FoodyPrice" name="element"
placeholder="Food Price" ></P>
<P><input type="button" value="Add Food" id="Btn_Close1" onclick="addFoodPrice(this.Foody, this.Pricey );"/>
<P><input type="button" value="Done Adding" id="Btn_Close1" onclick="doneAdd();"/>
</div>
<div id="slidess" style="display:block">
<P><input type="button" value="Input Name" id="Btn_Close" onclick="addName(this.UserName );"/></P>
</div>
</body>
</html>
I couldn't get your code snippet running here so I'm not able to immediately verify my suspicions in your code, but it looks like the problem might be from your myObject variable in the function displayArrayObjects(arrayObjects,outputName).
Make sure that myObject has the correct shape, i.e.
var myObject = {
name: 'John',
food: ['burger', 'cola'],
price: [3.5, 1.1]
}
myObject[x] might also be an object or array, so that might be why you're only printing out [object Object], so make sure you're iterating through every element of your object correctly. Use console.log to test the intermediate variables of your function to see if everything is in the correct format that you need. Hope this helps!

Take an input value and see if it equals the defined object

HTML:
<html>
<body>
<input type = "text" name = "name" id = "name"> </input>
<button type = "submit" id = "submit">Find Student </button>
<script type = "text/javascript" src="ObjectTest.js"></script>
</body>
</html>
Javascript:
var Matt = {
GPA: 4.0,
Faculty: "Science",
Year: 1
};
I have an object that I've defined with some values.
What I am trying to do is to allow text to be entered into the textbox.
When the submit button is hit, a javascript function will be run that grabs the value in the textbox and if it equals the object value, then it will console.log the properties.
Here is my better attempt:
function findStudent(){
var student = document.getElementById('name').value;
return student;
}
console.log(student);
Hard to know exactly what you're trying to achieve or where your object is coming from but your object probably needs to look something like:
var student = {
name:'Matt',
gpa:4.0,
faculty:'Science',
year: 1
}
Try something like:
function checkName(){
var name = document.getElementById('name').val();
if(name === student.name){
console.log('same');
}
else{
console.log('different');
}
}
Called in your button, with something like:
<button onclick="checkName()">Check Student</button>
You have to think about the structure. There should be a lot of students. It's not practical to set multiple objects for each student:
var st1 = { ... }
var st2 = { ... }
Instead it's more practical to declare one object with all students. And put the values in an array:
var students = {
"Matt": ["4.0", "science", "1.0"],
"Laura": ["3.0", "comedy", "2.2"],
...
}
You can output the array as an info to the corresponding student:
function findStudent() {
var info = [];
var student = document.getElementById("name").value;
for (name in students) {
if (name === student) {
info = students[name];
}
}
alert(info);
}
JSFiddle
If you want to use a submit button, it should be in a form. This also makes dealing with inputs easier, even if you don't want to submit the form. I've modified the object so that it has a name property.
var Matt = {
name: 'Matt',
GPA: 4.0,
Faculty: "Science",
Year: 1
};
function checkValue(form) {
if (form.studentName.value == Matt.name) {
form.output.value = ('Match');
} else {
form.output.value = ('Not a match');
}
return false;
}
<form onsubmit="return checkValue(this);">
<label for="studentName">Name: <input name="studentName" id="studentName"></label>
<button>Check the name</button>
<br>
<label for="output">Output: <input name="output" id="output"></label>
</form>
The body of the checkValue function could be:
form.output.value = form.studentName.value == Matt.name? 'Match' : 'Not a match';
However the longer version is simpler to understand.

value from HTML textbox to Javascript var

Hi want to store what user input into the textbox into my javascript var to be passed to my external PHP page,
I can pass the variable if i just define a value like mySite= 22 but not from what user enters into the text box.
Please help me to get access to the texbox.value
<form method="post" action="" onsubmit="submitFun(this)">
<input type="text" name="order_IDsearch" id="order_IDsearch"onBlur="javascript:setmysite(this);">
<input type="submit" />
</form>
<script type="text/javascript">
var mySite = '';
function setmysite(v1) {
var parent = document.getElementById('list');
var element = parent.GetElementsByTagName('order_IDsearch')[0];
mySite = element;
}
function submitFun(f1) {
t = './get_order.php?s=' + mySite;
t = encodeURI (t);
f1.action = t;
f1.submit();
return true;
}
You can try document.getElementById('order_IDsearch').value;

how to add the input values in an array

i just like to ask regarding adding data in a array. But the data which i wanted to put is from a table of input boxes.. Here's the code that i've been practicing to get data:
http://jsfiddle.net/yajeig/4Nr9m/69/
I have an add button that everytime I click that button, it will store data in my_data variable.
i want to produce an output in my variable something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}]
and if i would add another data again, it will add in that variable and it be something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"},
{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}]
the code that i have right now is really bad, so please help.
Currently my output:
1,4,6,4,1
You should be able to iterate over all of the textboxes using the following:
function add(e) {
var obj = {};
$('#addItem input[type="text"]')
.each(function(){obj[this.name] = this.value;});
myItems.push(obj);
}
Where myItems is a global container for your items and #addItem is your form.
Updated jsfiddle.
If you use a form and a submit button then you should be able to implement a non-JavaScript method to add your information so that the site will be accessible to people without JavaScript enabled.
Try this, sorry for modifying your form, but it works well:
HTML:
<form method="post" action="#" id="add_plank_form">
<p><label for="plank_number">Plank number</label>
<p><input type="text" name="plank_number" id="plank_number"/></p>
<p><label for="plank_width">Width</label>
<p><input type="text" name="plank_width" id="plank_width"/></p>
<p><label for="plank_length">Length</label>
<p><input type="text" name="plank_length" id="plank_length"/></p>
<p><label for="plank_thickness">Thickness</label>
<p><input type="text" name="plank_thickness" id="plank_thickness"/></p>
<p><label for="plank_quantity">Quantity</label>
<p><input type="text" name="plank_quantity" id="plank_quantity"/></p>
<p><input type="submit" value="Add"/>
</form>
<p id="add_plank_result"></p>
Javascript:
$(document).ready(function() {
var plank_data = Array();
$('#add_plank_form').submit(function() {
// Checking data
$('#add_plank_form input[type="text"]').each(function() {
if(isNaN(parseInt($(this).val()))) {
return false;
}
});
var added_data = Array();
added_data.push(parseInt($('#plank_number').val()));
added_data.push(parseInt($('#plank_width').val()));
added_data.push(parseInt($('#plank_length').val()));
added_data.push(parseInt($('#plank_thickness').val()));
added_data.push(parseInt($('#plank_quantity').val()));
$('#add_plank_form input[type="text"]').val('');
plank_data.push(added_data);
// alert(JSON.stringify(plank_data));
// compute L x W x F for each plank data
var computed_values = Array();
$('#add_plank_result').html('');
for(var i=0; i<plank_data.length; i++) {
computed_values.push(plank_data[i][1] * plank_data[i][2] * plank_data[i][3] / 12);
$('#add_plank_result').append('<input type="text" name="plank_add[]" value="' + computed_values[i] + '"/>');
}
return false;
});
});
Iterate through all keys, and add the values.
(code written from mind, not tested)
var added = { };
for (var i = 0; i < my_data.length; i ++) {
var json = my_data[i];
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (key in added) {
added[key] += json[key];
} else {
added[key] = json[key];
}
}
}
}
You can use the javascript array push function :
var data = [{plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}];
var to_add = [{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}];
data = data.concat(to_add);
Sorry I only glanced at the other solutions.
$(document).ready(function() {
var myData=[];
var myObject = {}
$("input").each(function() {
myObject[this.id]=this.value
});
alert(myObject["plank"])
myData.push(myObject)
});

Categories