Saving a couple of strings in the local storage - javascript

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));
}
};

Related

Javascript function innerText

I want to get the innerText of "lid" but when I write "lid.innerText I get null values is there any other way.
function zoom() {
var input = document.getElementById("myInput").value; //value from searchbox
// console.log(input);
d3.json("intervals.json", function(alldata) // entering json file to look for oid
{
var i;
for (i = 0; i < alldata.records.length; i++) //for loop for getting the oid alldata.records.length;
{
conceptid = alldata.records[i].oid; //saving all the oid in conceptid
lid = ("l" + conceptid.toString()); //concatenate with "l"
console.log(lid);
if (document.getElementById(lid).innerText === input) // if lid.innertext = input
{
document.getElementById(lid).click(); //then zoom
}
}
});
}
Your element is <text> which is a special tag inside <svg> so innerText does not apply. Use textContent instead:
if (document.getElementById(lid).textContent === input)

Changing location of html element dynamically using javascript

I am trying to change the pixel location of an html element using JavaScript. My function should take in a user input for the location and change the pixel coordinates according to an array.
This function should create a button at the user inputted location, but nothing happens. I think the issue is with setting a style attribute that requires both a text string and the variable that stores the location string. Any help would be appreciated.
var arr = [
["A1", "left:81px;"],
["A2", "left:145px;"]
]
function moveObject(arr) {
var location = prompt("Enter location", "A1");
var i;
for (let i = 0; i < arr.length; i++) {
if (arr[i][0] === location) {
destination = arr[i][1] + ";";
}
}
var box = document.createElement("button");
box.setAttribute("style", "position: absolute;");
box.setAttribute("style", destination)
box.innerText = location;
document.body.appendChild(box);
}
moveObject(arr)
Combine the css value strings and only call setAtrribute('style') once.
The second call wipes out the first
You are also adding an extra ; when it already exists in the value in your array.
Note I have not added any validation that the user entered value exists in the array. You will need to do that yourself before adding undefined values in the style
var arr = [
["A1", "left:81px;"],
["A2", "left:145px;"]
]
function moveObject(arr) {
var location = prompt("Enter location", "A1");
var i;
for (let i = 0; i < arr.length; i++) {
if (arr[i][0] === location) {
destination = arr[i][1] ;
}
}
var box = document.createElement("button");
// combine style values
box.setAttribute("style", "position: absolute;" + destination);
box.innerText = location;
document.body.appendChild(box);
}
moveObject(arr)
Several issues
I removed a stray " and added some text. Then I moved the left from the string and used the location as a lookup table instead
var arr = {
"A1": {"left":"81px"},
"A2": {"left":"145px"}
}
function moveObject(arr) {
var location = prompt("Enter location", "A1");
if (arr[location]) {
var box = document.createElement("button");
box.setAttribute("style", "position: absolute;");
var key = Object.keys(arr[location])
box.style[key] = arr[location][key]
box.innerText = location;
document.body.appendChild(box);
}
else alert("Location '"+location+"' not available")
}
moveObject(arr)

How can I display my var array name in HTML textblock?

I want to display my var array names in a textblock. These need to change depending on what box is ticked in my form.
Now I can show the values in the array, but I need to display the actual name too. I am VERY new to coding, and I have trouble finding the right words to describe my problem, thus not finding any solution. I hope you can help me out.
var color_prices = new Array();
color_prices["Orange"]=1;
color_prices["Blue"]=2;
color_prices["Green"]=3;
function getColorPrice()
{
var ColorPrice=0;
var theForm = document.forms["order-form"];
var selectedColor = theForm.elements["COLOR"];
for(var i = 0; i < selectedColor.length; i++)
{
if(selectedColor[i].checked)
{
ColorPrice = color_prices[selectedColor[i].value];
break;
}
}
return ColorPrice;
}
var colorPrice = getColorPrice();
document.getElementById('colorPrice').innerHTML = colorPrice.toFixed(2);
Right now I 'stole' some code online to display the value of "orange" in my html (so "1") and this works but I have no idea how to display the value "orange" in my html.
I hope I explained it correctly.
A solution could be to change your ColorPrice variable to be an object to be able to store the color price and the color name, in my example I'm also changing the name of the variable to colorDetails to be more descriptive about what is containing
var color_prices = new Array();
color_prices["Orange"]=1;
color_prices["Blue"]=2;
color_prices["Green"]=3;
function getColorDetails()
{
//here we rename the variable and convert from integer to object
var colorDetails = {
price: 0,
name: undefined
};
var theForm = document.forms["order-form"];
var selectedColor = theForm.elements["COLOR"];
for(var i = 0; i < selectedColor.length; i++)
{
if(selectedColor[i].checked)
{
//here we store the color price inside colorDetails
colorDetails.price = color_prices[selectedColor[i].value];
//and we add this new line where we save the name of the color
colorDetails.name = selectedColor[i].value;
break;
}
}
return colorDetails;
}
var colorDetails = getColorDetails();
document.getElementById('colorPrice').innerHTML = colorDetails.name + ": " + colorDetails.price.toFixed(2);

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

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();

How to prevent Javascript updating entire control, and refreshing content?

I have this code:
function addFormControls() {
var e = document.getElementById("ProductsList");
var prodid = e.options[e.selectedIndex].value;
var prodvalue = e.options[e.selectedIndex].text;
if (num == 0) {
document.getElementById("ProductsPanel").innerHTML = '<h3>Products added to Variant</h3>';
}
if (num < 10) {
var boolCheck = checkArrayData(prodid);
if (boolCheck == false) {
document.getElementById("ProductsPanel").innerHTML = document.getElementById("ProductsPanel").innerHTML + prodvalue + '<input type="text" id="' + prodid + 'product" value="0" width="50px" maxlenght="2" /><input type="button" onclick="updateArrayData(\'' + prodid + '\', document.getElementById(\'' + prodid + 'product\').value);" value="Update Number" /><br />';
num++;
prodIdArray.push({
'key': prodid,
'value': prodvalue,
'num': 0
});
document.getElementById("productsArray").value = prodIdArray;
} else {
alert("Sorry product has already been added!");
}
}
}
which happily updates a div tag with new info, however if you look at the section where it prints a text box to the screen, line 13, these textbox's will be updated by the user.
So in short, textboxs are added, and value update.
however if there is a textbox with value 5, then this function called again to add another textbox, the previous textbox' values will be wiped clean!
So, how do i prevent this, will i have to do some, for loop over div controls taking the values, then put them back after this function is called?!?
I create some javascript to save all the values in a particular input's value field before adding the control, then return all the saved values back to their respected inputs.
function saveValuesOfProducts()
{
// initialise the array
numOfProds = new Array();
// get all the elements which are inputs
var x=document.getElementsByTagName("input");
// remove all un necessary inputs
x = leaveTextInputs(x);
// loop through the entire list of inputs left saving their value
for (i=0; i<x.length; i++)
{
numOfProds.push(x[i].value);
}
}
function returnValuesOfProducts()
{
// get all the elements which are inputs
var x=document.getElementsByTagName("input");
// remove all un necessary inputs
x = leaveTextInputs(x);
// loop through the entire list of saved values and return them to the input
for (i=0; i<numOfProds.length; i++)
{
x[i].value = numOfProds[i];
}
}
function leaveTextInputs(value)
{
// create a new blank array
var newArr = new Array();
// loop through all the elements in passed array
for (i=0; i<value.length; i++)
{
// cache the element
var thevalue = value[i];
// check if the element is a text input
if (thevalue.type == "text")
{
// check the id consists of product in it!
var regexteststring = thevalue.id;
// create the pattern to match
var patt1 = /product/i;
if (regexteststring.match(patt1) == "product")
{
// as additional check, if it has a size quantity of 2 then its defo out stuff
if (thevalue.size == 2)
{
newArr.push(thevalue);
}
}
}
}
// now return the new array
return newArr;
}

Categories

Resources