Storage and show multiple outputs - javascript

I have a simple text input where users type anything and after sumbitting text appear on a page and stays there, which I done with localStorage, but after refreshing the page only last typed input is showing, Ill post my code to be more specific:
HTML:
<body>
<input id="NewPostField" type="text" value="">
<button onclick="myFunction()">Post</button>
<div id="Posts"></div>
</body>
JavaScript:
function myFunction() {
var NewPostField =
document.getElementById("NewPostField");
var newPost = document.createElement("p");
localStorage.setItem('text',
NewPostField.value);
newPost.innerHTML = NewPostField.value;
var Posts = document.getElementById("Posts");
Posts.appendChild(newPost);
}
(function() {
const previousText = localStorage.getItem('text');
if (previousText) {
var NewPostField = document.getElementById("NewPostField");
NewPostField.value = previousText;
myFunction();
}
})();
Any help will be great!

It seems that your code is only storing the last value posted.
To store more than one post, one idea is to stringify an array of values to store in localStorage.
Then, parse that stringified value back into an array as needed.
Here's an example:
function getExistingPosts() {
// fetch existing data from localStorage
var existingPosts = localStorage.getItem('text');
try {
// try to parse it
existingPosts = JSON.parse(existingPosts);
} catch (e) {}
// return parsed data or an empty array
return existingPosts || [];
}
function displayPost(post) {
// display a post
var new_post = document.createElement("p");
new_post.innerHTML = post;
posts.appendChild(new_post);
}
function displayExistingPosts() {
// display all existing posts
var existingPosts = getExistingPosts();
posts.innerHTML = '';
inputPost.value = '';
if (existingPosts.length > 0) {
existingPosts.forEach(function(v) {
displayPost(v);
});
inputPost.value = existingPosts.slice(-1)[0];
}
}
function addPost(post) {
// add a post
var existing = getExistingPosts();
existing.push(post);
localStorage.setItem('text', JSON.stringify(existing));
displayPost(post);
}
function clearPosts() {
// clear all posts
localStorage.removeItem('text');
displayExistingPosts();
}
var posts = document.getElementById("posts");
var inputPost = document.getElementById("input_post");
var btnPost = document.getElementById('btn_post');
var btnClear = document.getElementById('btn_clear');
btnPost.addEventListener('click', function() {
addPost(inputPost.value)
});
btnClear.addEventListener('click', clearPosts);
displayExistingPosts();
<input id="input_post" type="text" value="">
<button type="button" id="btn_post">Post</button>
<button type="button" id="btn_clear">Clear</button>
<div id="posts"></div>
Since localStorage isn't supported in StackSnippets, here's a JSFiddle to help demonstrate.

Related

Sort JSON response objects alphabetically

Just trying to get some practice working with public APIs in Javascript. All I want to do is, when you submit the query, have the list of items I get back be sorted alphabetically by the h4 value (food name). I tried calling .sort() on the response item before calling .map(). Tried directly sorting the div elements after the fact using jquery, but in both cases, I just get a blank page back. I'm very new to javascript and writing this all in Notepad++, so there's probably a much better way to be doing all this, but I'm not aware of it.
Html code:
<!DOCTYPE html>
<html>
<form action="search">
<label>Search</label>
<input type="text">
<input type="submit">
<input type="reset">
</form>
<div class="result">
<h3>Result</h3>
</div>
</html>
Css code:
.result{
display:flex;
flex-wrap:wrap;
}
.item{
min-width:200px;
margin:20px auto;
}
JavaScript code:
var apiKey = "4b314d3e9171fbe99c6cdf16127ba93e";
var apiId = "4c143c55";
var queryItem;
var url = 'https://trackapi.nutritionix.com/v2/search/instant?query=';
var form = document.querySelector('form');
var input = document.querySelector('input[type="text"]');
var result = document.querySelector('.result');
function search(e){
e.preventDefault();
queryItem = input.value;
makeRequest(queryItem);
input.value= "";
}
function reset(){
var node = document.querySelector('.result');
while (node.firstChild) {
node.removeChild(node.firstChild);
}
}
function createFood(name, qty, unit, photo){
var item = document.createElement('div');
var foodName = document.createElement('h4');
var serving = document.createElement('p');
var img = document.createElement('img');
item.classList.add('item');
foodName.innerHTML = name;
serving.innerHTML = qty+' '+unit;
img.src = photo;
result.appendChild(item);
item.appendChild(img);
item.appendChild(foodName);
item.appendChild(serving)
}
function makeRequest(queryItem) {
reset();
xhr = new XMLHttpRequest();
xhr.onload = function() {
var response = JSON.parse(this.responseText);
response.common.map(function(food){
createFood(food.food_name,
food.serving_qty,
food.serving_unit,
food.photo.thumb
)
})
};
xhr.open(
"GET",
url+queryItem,
true
);
xhr.setRequestHeader('x-app-id',apiId);
xhr.setRequestHeader('x-app-key',apiKey);
xhr.send();
}
form.addEventListener('submit', search)
form.addEventListener('reset', reset)
You can use a generic function to sort by the attribute of your choice.
function sortByAttrAlphabeticallyASC(arr, attr) {
return arr.sort((a, b) =>
a[attr].toLocaleLowerCase().localeCompare(b[attr].toLocaleLowerCase())
);
}
Where arr is the array of Objects you want to sort and attr is the name of the attribute that will be compared.
As you can see here Array has a method that you can pass a callback with the comparation.
And String has a method to compare Strings as seen here witch can be passed inside Array::sort for comparation purposes.
In your case you would do:
sortByAttrAlphabeticallyASC(response.common, 'name').forEach(food => createFood(food.food_name,
food.serving_qty,
food.serving_unit,
food.photo.thumb
))

Append localstorage data to the body element on All session (Works also with reload)

I have some code from input, and I wanna to save it to some body element.
I can add it to the body, but it disappear when page is reloaded
function store(){
var nameOfbook = document.getElementById("nameOfbook");
var value = localStorage.setItem("nameOfbook", nameOfbook.value);
var storedValueBockName = localStorage.getItem("nameOfbook");
var par = document.createElement('P');
par.innerText = storedValueBockName;
document.body.appendChild(par);
}
<form action="\" class="form-login" method="post" />
<input name="text" type="text" id="nameOfbook" required="" placeholder="Book name" />
<button onclick="store()" type="button">StoreText</button>
</form>
This question is basically asking how to retrieve a stored value from localStorage.
So you're setting the value in localStorage, but when you reload the page, you need to have a script that checks to see if there's a value in localStorage and add that data to your page if it is found there.
I would suggest something like:
<script>
var setText = function(text) {
var par = document.createElement('P');
par.innerText = text;
document.body.appendChild(par);
}
var checkLocalStorage = function() {
var value = localStorage.getItem("nameOfbook")
if (value) {
setText(value)
}
}
checkLocalStorage()
function store(){
var nameOfbook = document.getElementById("nameOfbook");
var value = localStorage.setItem("nameOfbook", nameOfbook.value);
var storedValueBockName = localStorage.getItem("nameOfbook");
setText(storedValueBockName)
}
</script>
So I moved the code that appends the title to the page into its own function so that it can be used by both store() and checkLocalStorage(). checkLocalStorage looks to see if there's a value set for nameOfbook and, if there is, passes that value to setText.
Should do the trick.

Best way to store Local Storage?

I've made a start to a to do list. I've got it adding an item when you submit an item.
I want to now add local storage when you refresh the page so the items are saved in the browser.
I obviously need to save all the times when the page is refreshed but because my items only update on click I'm not sure how to grab that function data outside the function and save the items.
Any ideas?
Cheers
JS Fiddle:
https://jsfiddle.net/x1bj8mfp/
// When submit item
var submit = document.getElementById('form');
submit.addEventListener('submit', addItem);
var items = [];
var itemValues = document.getElementById('items');
var listContainer = document.createElement('ul');
itemValues.appendChild(listContainer);
// Add item
function addItem(e) {
e.preventDefault();
var item = this.querySelector('[name=item]');
var itemValue = item.value;
items.push(itemValue);
item.value = '';
// Output items
var listItems = document.createElement('li');
listItems.innerHTML = itemValue;
listContainer.appendChild(listItems);
}
You could write the whole array to local storage whenever you add an item:
localStorage.setItem('items', JSON.stringify(items));
Then on page load you would read from local storage the array and assign it back to your variable, or set it to [] (like now), if nothing is in local storage, and then display these items:
var items = JSON.parse(localStorage.getItem('items')) || [];
items.forEach(function (itemValue) {
var listItems = document.createElement('li');
listItems.textContent = itemValue;
listContainer.appendChild(listItems);
});
This updated JSFiddle has that code included.
Of course, you will need some function to delete items as well, otherwise you can only grow your list.
Here's a full solution for you. Note that the code snippet won't work here, due to the cors and sandbox. Just paste it into your code editor.
var submit = document.getElementById('form');
submit.addEventListener('submit', addItem);
var items = [];
var itemValues = document.getElementById('items');
var listContainer = document.createElement('ul');
itemValues.appendChild(listContainer);
//retrieve data after reload
window.onload = function() {
if (localStorage.userData != undefined) {
var userData = JSON.parse(localStorage.getItem('userData'));
for (var i = 0; i < userData.length; i++) {
var listItems = document.createElement('li');
listItems.innerHTML = userData[i];
listContainer.appendChild(listItems);
items = userData;
}
}
}
// Add item
function addItem(e) {
e.preventDefault();
var item = this.querySelector('[name=item]');
var itemValue = item.value;
items.push(itemValue);
item.value = '';
// Output items
var listItems = document.createElement('li');
listItems.innerHTML = itemValue;
listContainer.appendChild(listItems);
localStorage.setItem('userData', JSON.stringify(items));
}
<main>
<form id="form">
<input class="form-input" type="text" name="item" placeholder="Add item">
<input class="btn btn-block" type="submit" value="Submit">
</form>
<div id="items"></div>
<div id="completed"></div>
</main>
Here some helpful small example for local storage
function save() {
var fieldvalue = document.getElementById('save').value;
localStorage.setItem('text', fieldvalue);
}
function load() {
var storedvalue = localStorage.getItem('textfield');
if (storedvalue) {
document.getElementById('textfield').value = storedvalue;
}
}
function remove() {
document.getElementById('textfield').value = '';
localStorage.removeItem('textarea');
}
<body onload="load()">
<input type="textarea" id="textfield">
<input type="button" value="Save" id="save" onclick="save()">
<input type="button" value="remove" id="remove" onclick="clr()">
</body>
<!--save& run this in local to see local storage-->

LocalStorage array

Guys help me with this code. The idea is to save new inputs in a string and display them using HTML. Every time I add a new one the HTML displays it, if I reload the page the items are still displayed and the first getItem method and if I reload again is still working but here is the problem. After I reload the page and I insert a new element in string then it will display the just the lates inputs and will delete the ones from other sessions.
If I insert now :"one","two","three" it I will display "one,two,three" if I reload it will still display " one,two,three" which is good, but after the reload if I insert "four" it will display only "four" and I want to be displayed "one,two,three,four".
How can I make this happen?
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<button onclick="reloadd()">Reload</button>
<button onclick="clearF()">Clear</button>
<input id="valoare">
<button id="adauga" onclick="adauga()">+</button>
<button onclick="nrElemente()">ElemNr?</button>
<script>
var cars = [];
var two = "kes";
document.getElementById("result").innerHTML = localStorage.getItem("array1");
function clearF() {
window.localStorage.clear();
location.reload();
}
function adauga() {
var x = document.getElementById('valoare').value;
cars.push(x);
localStorage.setItem("array1", cars);
document.getElementById("result").innerHTML = localStorage.getItem("array1");
}
function reloadd() {
location.reload();
}
function nrElemente() {
alert(localStorage.length);
}
</script>
</body>
</html>
Your code is not working because you are not storing your array anywhere.
To save your array into localStorage you would use:
localStorage.setItem("cars", JSON.stringify(cars));
Then instead of doing this:
var cars = [];
You would load your cars array like this:
var cars = localStorage.getItem("cars");
cars = (cars) ? JSON.parse(cars) : [];
What this is doing is, it is checking if the localStorage object contains an array called cars. Now if it does it will parse that string and return the stored cars array, if it does not it will set the cars array to a new empty array.
Here, I have fixed and tidied your code:
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<button onclick="reloadd()">Reload</button>
<button onclick="clearF()">Clear</button>
<input id="valoare" />
<button id="adauga" onclick="adauga()">+</button>
<button onclick="nrElemente()">ElemNr?</button>
<script type="text/javascript">
var array1 = localStorage.getItem("array1");
array1 = (array1) ? JSON.parse(array1) : [];
var two = "kes";
document.getElementById("result").innerHTML = localStorage.getItem("array1");
function clearF() {
window.localStorage.clear();
location.reload();
}
function adauga() {
var x = document.getElementById("valoare").value;
array1.push(x);
localStorage.setItem("array1", JSON.stringify(array1));
document.getElementById("result").innerHTML = localStorage.getItem("array1");
}
function reloadd() {
location.reload();
}
function nrElemente() {
alert(localStorage.length);
}
</script>
</body>
</html>
Also, it's considered bad practice to place your JavaScript events & functions in HTML attributes. Try to separate HTML, CSS & JS as much as possible by placing all (or at-least most) of your JS in your script element / JS file.
Good luck and all the best.
You are creating an empty array every page load and when you add to array you store that but never connect cars array to the data that is already stored
Try changing
var cars =[];
To
var localData = localStorage.getItem("array1");
// if localData not undefined then parse that as cars array, otherwise is empty array
var cars = localData ? JSON.parse(localData) : [];
When you go to store the cars array change to:
localStorage.setItem("array1",JSON.stringify(cars));
There were some major issues with your code, this is a fixed version:
<script type="text/javascript">
var cars = [];
try {
cars = JSON.parse(localStorage.getItem("array1"));
} catch (err) {}
var two = "kes";
document.getElementById("result").innerHTML = cars;
function clearF() {
window.localStorage.clear();
location.reload();
}
function adauga() {
var x = document.getElementById('valoare').value;
cars.push(x);
localStorage.setItem("array1", JSON.stringify(cars));
document.getElementById("result").innerHTML = localStorage.getItem("array1");
}
function reloadd() {
location.reload();
}
function nrElemente() {
alert(localStorage.length);
}
</script>

add values to textbox history without submitting the form using javascript or Jquery

Hello friends I have a <input type="text" id="tempID" /> element in my form
I also have an <input type="button" onclick="doSomething()" /> element in my form.
I want to add the text box value to textbox history when user clicks on the button.
I am processing the request using Jquery ajax. So I have to do it with javascript or Jquery.
Is this possible to add values to the history of particular <input type="text" /> element using javascript/Jquery..??
Here is how you can do it using HTML5 LocalStorage
$( "#tempID" ).autocomplete({
source: function( req, resp ) {
var temp = localStorage.getItem('custom_history');
var data = JSON.parse(temp);
resp( data );
}
});
$('#tempID').on('blur', function() {
var temp = localStorage.getItem('custom_history');
var data = JSON.parse(temp);
if($.trim(this.value).length > 0)
data.push(this.value);
localStorage.setItem('custom_history', JSON.stringify(data));
});
What I am doing is Setting the value into HTML5 Local storage when users moves away from the input field, clicks somewhere else.
Then retrieving that and setting that as source for jQuery UI auto complete.
Here is a working fiddle http://jsfiddle.net/joycse06/EBduF/173/
Enter some value. Click somewhere else. Click back again and add other values. The refresh the fiddle and start typing one of those and auto complete will show up.
UPDATE
Based on his comments and later chat the final code he need is this, I am pasting in if it might someone else later
// if we dont set this line then ff will return null, and null.length will throw an error
if(!localStorage.getItem('custom_history'))
localStorage.setItem('custom_history','');
$( "#test" ).autocomplete({
source: function( req, resp ) {
var term = req.term;
var temp = localStorage.getItem('custom_history');
var data = [];
if(temp.length > 0)
data = JSON.parse(temp);
var intRegex = /^\d+$/;
data = $.map(data,function(val){
if(intRegex.test(val)){
if(val.indexOf(term) != -1)
return val;
else
return null;
}
else
return null;
});
resp( data );
}
});
$('#save').on('click', function() {
var temp = localStorage.getItem('custom_history');
var data = [];
if(temp.length > 0)
data = JSON.parse(temp);
var value = $.trim($('#test').val());
if(value.length > 0){
if($.inArray(value,data) != -1){
//alert('Duplicate');
return;
}
}
data.push(value);
localStorage.setItem('custom_history', JSON.stringify(data)); // set item to localStorage
});
You can use localStorage like following:
var arr = [];
$('input#tempID').on('click', function() {
arr.push(this.value);
localStorage.setItem('history', JSON.stringify(arr)); // set item to localStorage
});
To retrieve that value try,
var temp = localStorage.getItem('history');
if(retarr) { // checking that data it stored in localStorage or not, if not exists temp = null
var allHistories = JSON.parse(temp); // now you have history
console.log(allHistories);
}
I think you need something like autocomplete

Categories

Resources