After setting localstorage item, can't show it on screen - javascript

I basicly add my input values to vals array.
Then save the array to localStorage: localStorage.setItem('mylist', JSON.stringify(vals));
After that, i show values from vals array.
It saves the values to localStorage but when i refresh, values doesn't show up on screen with my dynamicly created li elements.
Why?
Note: I want to use localstorage with JSON.
JSFIDDLE
var input = document.getElementById("input");
var box = document.querySelector(".box");
var vals = [];
var li;
var list;
input.addEventListener("keyup", function(e) {
var val = e.target.value;
if (e.which == 13) {
box.innerHTML = "";
input.value = " ";
// Push input value array
vals.push(val);
localStorage.setItem('mylist', JSON.stringify(vals));
// Loop input values
list = vals.map(function(item, index) {
li = document.createElement("LI");
box.appendChild(li);
li.innerHTML = JSON.parse(localStorage.getItem('mylist'))[index];
});
}
}, false);
box.innerHTML = list;

After a page refresh the list array is empty. this will fix it:
var vals = JSON.parse(localStorage.getItem('mylist') || "[]");
vals.forEach(function(entry) {
li = document.createElement("LI");
box.appendChild(li);
li.innerHTML = entry;
})
The || "[]" is a fallback in case localStorage returns null (the user never set a list)
You should also remove the last line of your script ( box.innerHTML = list; )

Youd don't read anything from localStorage after page load. You read data from storage only in your keyup handler but you do it right after overriding it with new value. You have to get data from storage when page is loaded:
use this:
var list = JSON.parse(localStorage.getItem('mylist'))

It is saving in localStorage but in your code, after you refresh, you never populate the values in your HTML.
var input = document.getElementById("input");
var box = document.querySelector(".box");
var storageVals = localStorage.getItem('mylist');
var vals = storageVals ? JSON.parse(storageVals) : [];
input.addEventListener("keyup", function(e) {
var val = e.target.value;
if (e.which == 13) {
box.innerHTML = "";
input.value = " ";
// Push input value array
vals.push(val);
localStorage.setItem('mylist', JSON.stringify(vals));
renderList();
}
}, false);
function renderList() {
// Loop input values
vals.forEach(function(item, index) {
var li = document.createElement("LI");
box.appendChild(li);
li.innerHTML = JSON.parse(localStorage.getItem('mylist'))[index];
});
}
renderList();

Related

Saving a couple of strings in the local storage

I'm trying to save some strings in the local storage, I'm trying to do this but I get undefined in the local storage.
I'm asking the user for the players names, and then I want to store them in the local storage in order to use them again.
Here's what I'm trying :
const x = localStorage.getItem('playersNum');
const parentDiv = document.getElementById('player-list');
for (let i = 0; i < x; i++) {
const newInput = document.createElement("INPUT");
newInput.setAttribute("type", "text");
newInput.setAttribute("class", "form-control");
newInput.setAttribute("id", `player${i}`);
newInput.setAttribute("placeholder", "Player's Name");
parentDiv.appendChild(newInput);
}
//get all input elements of type text and starting id with player
const input = document.querySelectorAll("[type='text'][id^='player']");
const btn = document.getElementById('startGame');
btn.addEventListener('click', function() {
//reset border style of all input elements
[...input].forEach(el => el.style.border = '');
//get all empty input elements
let empty = [...input].filter(el => el.value.trim() == "");
//check length
if (empty.length) {
//show alert
// alert('Please fill in the players names');
//set border style to empty input elements
empty.forEach(el => el.style.border = '1px solid red');
}
else {
window.location.assign('game.html');
localStorage.setItem('playersNames', String(input.value));
}
});
You're declaring input with querySelectorAll, so you need to read input as an array.
localStorage.setItem('playersNames', String(input[0].value));
Then, if you want all player's names you will need to iterate through the array. Also, you need to get the previous value of localStorage and append to it, since it gets overwritten every time you set it.
const input = document.querySelectorAll("[type='text'][id^='player']");
for (i=0; i < input.length; i++) {
var checkForStorage = localStorage.getItem('playersNames');
if (checkForStorage !== null) {
localStorage.setItem('playersNames', checkForStorage + ',' + String(input[i].value))
} else {
localStorage.setItem('playersNames', String(input[i].value));
}
};

Adding a listener to a button created by .innerHTML

I am trying to add a listener to a button created by .innerHTML after receiving a listener. This is the code:
let inputConfirm = document.getElementById('inputConfirm');
let inputText = document.getElementById('inputText');
let displayList = document.getElementById('displayList');
inputConfirm.addEventListener('click', e=>listElement())
const listElement = () => {
let inputValue = inputText.value //takes input from textbox
let newValue = "<li class='each-item'><div class='listbox'>" + inputValue + "<input type='checkbox' class='checkbox'><button class='delete-button'>X</button></div></li>"; //EACH list element that I want to add to the ordered list.
if(inputValue !== ""){
displayList.innerHTML += newValue;
inputText.value = "";//clears the text box
};
};
I need the button with class "delete-button" created via newValue variable to be clickable and send a console.log
It's unclear what you want to output in the console but the simple way is to add onclick event into .innerHTML and add a function.
let inputConfirm = document.getElementById('inputConfirm');
let inputText = document.getElementById('inputText');
let displayList = document.getElementById('displayList');
inputConfirm.addEventListener('click', e=>listElement())
const listElement = () => {
let inputValue = inputText.value //takes input from textbox
let newValue = "<li class='each-item'><div class='listbox'>" + inputValue + "<input type='checkbox' class='checkbox'><button class='delete-button' onclick='toConsole(event)'>X</button></div></li>"; //EACH list element that I want to add to the ordered list.
if(inputValue !== ""){
displayList.innerHTML += newValue;
inputText.value = "";//clears the text box
};
};
function toConsole(e){
console.log(e.target);
}

Automatically adding extra space to result and Uncaught TypeError: Cannot read property 'keyCode' of undefined

I am learning JavaScript.
I have created a input and a button. So whenever user type anything in the input it will show in the list item. It is working as expected but the automatic space and console error is bugging me.
Automatic space :- The first result has no space between 1 and Rahul. Whereas other result have space between them. The results are added in list item in two different events.
1) On Enter key press
2) On click on add new button
Console error
document.getElementById('user_input').focus();
function onPress_ENTER()
{
var keyPressed = event.keyCode || event.which;
//if ENTER is pressed
if(keyPressed==13)
{
incre();
keyPressed=null;
}
else
{
return false;
}
}
var count = 0;
onPress_ENTER();
function incre(){
count += 1;
var text = document.createTextNode(count);
var el = document.createElement("li");
//get text from input box and create node
var user_input = document.getElementById('user_input').value;
var user_input_node = document.createTextNode(user_input);
//create element node span and add user input inside span
var user_el = document.createElement('span');
user_el.appendChild(user_input_node);
//id of list item element
var id_el = document.getElementById('list_item');
//append counter inside the li
el.appendChild(text);
el.appendChild(user_el);
id_el.appendChild(el);
document.getElementById('user_input').value = " ";
document.getElementById('user_input').focus();
}
<input type="text" id="user_input" onkeypress="onPress_ENTER()">
<input type="button" onclick="incre()" value="add new">
<ul id="list_item">
</ul>
Your issue is on how you organized your code.
You can call the function onPress_ENTER only at document ready.
For the event I suggest you to pass it directly in the inline call.
Instead of keyPressed=null; you can use preventDefault.
In order to reset the input field you can write:
// reset input
document.getElementById('user_input').value = "";
document.getElementById('user_input').focus();
but, when you need to add this to the list you can change this line:
var user_input = document.getElementById('user_input').value;
to:
var user_input = " " + document.getElementById('user_input').value;
The example:
// when document is ready
document.addEventListener('DOMContentLoaded', function(e) {
document.getElementById('user_input').focus();
onPress_ENTER(e); // this is useless.....
});
// global func and var
function onPress_ENTER(e) {
var keyPressed = e.keyCode || e.which;
//if ENTER is pressed
if (keyPressed == 13) {
e.preventDefault();
incre();
}
}
var count = 0;
function incre() {
count += 1;
var text = document.createTextNode(count);
var el = document.createElement("li");
//get text from input box and create node
var user_input = " " + document.getElementById('user_input').value;
var user_input_node = document.createTextNode(user_input);
//create element node span and add user input inside span
var user_el = document.createElement('span');
user_el.appendChild(user_input_node);
//id of list item element
var id_el = document.getElementById('list_item');
//append counter inside the li
el.appendChild(text);
el.appendChild(user_el);
id_el.appendChild(el);
// reset input
document.getElementById('user_input').value = "";
document.getElementById('user_input').focus();
}
<input type="text" id="user_input" onkeypress="onPress_ENTER(event)">
<input type="button" onclick="incre()" value="add new">
<ul id="list_item">
</ul>
here: var count = 0; onPress_ENTER(); you call a function without event. You need to remove this call
look at jsfiddle
document.getElementById('user_input').focus();
function onPress_ENTER()
{
var keyPressed = event.charCode || event.which;
//if ENTER is pressed
if(keyPressed==13)
{
incre();
keyPressed=null;
}
else
{
return false;
}
}
var count = 0;
function incre(){
count += 1;
var text = document.createTextNode(count);
var el = document.createElement("li");
//get text from input box and create node
var user_input = document.getElementById('user_input').value;
var user_input_node = document.createTextNode(user_input);
//create element node span and add user input inside span
var user_el = document.createElement('span');
user_el.appendChild(user_input_node);
//id of list item element
var id_el = document.getElementById('list_item');
//append counter inside the li
el.appendChild(text);
el.appendChild(user_el);
id_el.appendChild(el);
document.getElementById('user_input').value = " ";
document.getElementById('user_input').focus();
}

How the heck do I do string comparison from a list item to the items in an array

I am attempting to take the contents of an individual list items in one UL and when one is clicked add the value of that individual LI to an array and append the text string of the list item to an ordered list item somewhere else on the page.
I am having trouble comparing the string of the clicked LI,iterating through the array to make sure the string of the LI listed once, and then adding the text to the OL. Help appreciated.
var list = $('.list'),
listItem = $('.list li'),
container = $('.list-content ul'),
containerItem = $('.list-items li');
itemArray = [];
listItem.on({
'click' : function(){
var current = $(this),
currentText = $(this).text();
if( itemArray.length <= 0 ) {
itemArray.push(currentText);
$('<li>'+ currentText + '</li>').appendTo(container); //add text to new area
}else{
for( var count = 0; count < itemArray.length; count++){
if( currentText === itemArray[count] ){
return false;
break;
} else {
itemArray.push(currentText);
$('<li>'+ currentText + '</li>').appendTo(container); //add text to new area
break;
}
}
}
}//end of click function
});
You can use $.inArray() to check whether an object is present in an array
this should do
var list = $('.list'),
listItem = $('.list li'),
container = $('.list-content ul'),
containerItem = $('.list-items li'),
itemArray = [];
listItem.on({
'click' : function(){
var current = $(this),
currentText = $(this).text();
if($.inArray(currentText, itemArray) == -1){
itemArray.push(currentText);
$('<li>'+ currentText + '</li>').appendTo(container); //add text to new area
}
}//end of click function
});
Demo: Fiddle

JavaScript: Getting the right UI element in a list of them

I am building a UI in JavaScript that involves adding a column of checkBoxes:
for (var key in ProcessAndPortList.list)
{
if (ProcessAndPortList.list.hasOwnProperty(key))
{
var dataRow = myTable.insertRow(-1);
var dataCell = dataRow.insertCell(-1);
dataCell.textContent = key;
dataCell = dataRow.insertCell(-1);
dataCell.textContent = ProcessAndPortList.list[key].port;
var terminationCheckbox = document.createElement('input');
terminationCheckbox.type = "checkbox";
terminationCheckbox.id = key;
terminationCheckbox.checked = ProcessAndPortList.list[key].markedForTermination;
terminationCheckbox.onchange = function() {
var isChecked = terminationCheckbox.checked;
markForTermination(key, isChecked);
};
var terminateCell = dataRow.insertCell(-1);
terminateCell.appendChild(terminationCheckbox);
}
}
The problem comes in associating the correct ID to the callback for when the checkbox for each entry is checked. I can't seem to get that checkbox's ID to the function. I only ever get the last checkBox's ID. How can I get the correct ID?
Changing this should work:
terminationCheckbox.onchange = function() {
markForTermination(this.id, this.checked);
};
It seems that you capture the variable key with that closure. But key changes on each iteration of the for loop. Capture some variable that is declared inside the loop instead.
for (var key in ProcessAndPortList.list)
{
if (ProcessAndPortList.list.hasOwnProperty(key))
{
var local_scope_key = key
var dataRow = myTable.insertRow(-1);
var dataCell = dataRow.insertCell(-1);
dataCell.textContent = key;
dataCell = dataRow.insertCell(-1);
dataCell.textContent = ProcessAndPortList.list[key].port;
var terminationCheckbox = document.createElement('input');
terminationCheckbox.type = "checkbox";
terminationCheckbox.id = key;
terminationCheckbox.checked = ProcessAndPortList.list[key].markedForTermination;
terminationCheckbox.onchange = function() {
var isChecked = terminationCheckbox.checked;
markForTermination(local_scope_key, isChecked);
};
var terminateCell = dataRow.insertCell(-1);
terminateCell.appendChild(terminationCheckbox);
}
}

Categories

Resources