i need when i click on input then must prompt and result transferred to storage, help me please, i tried to find this resolve in google but no use:(
const output = document.querySelector('[data-output]');
const LOCAL_STORAGE_LIST_KEY = 'task.lists';
const LOCAL_STORAGE_SELECTED_LIST_ID_KEY = 'task.selectedListId';
let lists = JSON.parse(localStorage.getItem(LOCAL_STORAGE_LIST_KEY)) || [];
let selectedListId = localStorage.getItem(LOCAL_STORAGE_SELECTED_LIST_ID_KEY);
output.addEventListener('click', e => {
let txt = prompt('Enter what you want to do ^^').toString();
lists.push(txt);
saveAndRender();
});
Your error seems to be in the renderLists function, which is on the JSFiddle that you linked in the comments. You're looping over your lists Array, which contains the input String - But you're trying to access properties as if it was an Object; which is instead giving you undefined
You have createListwhich will turn that input into an Object with the current keys, so I assume you meant to include that
output.addEventListener('click', e => {
let txt = prompt('Enter what you want to do ^^').toString();
lists.push(createList(txt));
saveAndRender();
});
Here is an updated JSFiddle
Related
there are many questions with nearly the same title with this errors. i read them but seems different.
If I use a string directly in the function historyDatabase, it works.
If i using the string in an array function historyDatabase, it works.
If I take the string from the config file, I can output it and it looks correct (I use the error function for this).
I don't understand why the string from config causes problems here, but the same string in plain text doesn't cause any problems. Any idea?
let player = "";
player = Engine.ConfigDB_GetValue("user", "localratings.save.searchplayerinput");
error("player = ---" + player + "---"); // this output is correct seeh
// const playerData = this.historyDatabase["seeh"]; // this works
// const playerData = this.historyDatabase[["seeh"]]; // this works
// const playerData = this.historyDatabase[player]; // this produce errors
// const playerData = this.historyDatabase[[player]]; // this produce errors
// const playerData = this.historyDatabase[{player}]; // this produce errors
const playerData = this.historyDatabase[player]; // this produce errors
its part of this source https://gitlab.com/sl5net/LocalRatings/-/commit/891696adebcdd9fffbfce0a889808a3742e8992d used in a open-source game.
The error-screenshot
the hard-coded example string was implicitly converted into an object.
the example array was implicitly converted to an object.
but the string from the text file was not automatically converted.
I do not know why.
the solution was to pass the string from the config file as an object.
let playerObj = {};
playerObj = Engine.ConfigDB_GetValue("user", "localratings.save.searchplayerinput");
const playerData = this.historyDatabase[playerObj];
I'm currently in the process of passing a javascript array though to a form for submission with a file upload.
As it currently stands i have been able to pass the javascript array though to the form but not quite how i would like.
The initial javascript values i have stored in the array are as follows:
Folder 1/File 1.txt
Folder 1/Folder 2/File 2.txt
Once passed though the array output from the PHP variable is as follows:
Array ( [0] => Folder 1/File 1.txt,Folder 1/Folder 2/File 2.txt )
What i would like to do however if possible is alter the array to the following:
Array ( [0] => Folder 1/File 1.txt,
[1] => Folder 1/Folder 2/File 2.txt )
The HTML code the array is being passed to from javascript:
<input type="hidden" id="pathArray" name="pathArray[]" value="pathArray">
The current javascript code:
let picker = document.getElementById('picker');
var pathStructure = [];
var i = 0;
picker.addEventListener('change', e =>
{
for (let file of Array.from(e.target.files))
{
pathStructure[i] = file.webkitRelativePath;
i++;
};
document.getElementById('pathArray').value = pathStructure.toString();
});
The main issue i'm having and at the moment is setting the array position values of the form for submission. I'm able to input the array into the form but not able to set the individual array positions and as of yet have been unable to find the relevant documentation on how to achieve this somehow like the following:
let picker = document.getElementById('picker');
var pathStructure = [];
var i = 0;
picker.addEventListener('change', e =>
{
for (let file of Array.from(e.target.files))
{
pathStructure[i] = file.webkitRelativePath;
document.getElementById('pathArray').value[i] = pathStructure[i].toString();
i++;
};
});
Any help would be greatly appreciated and if at all there is any further detail that would be required please let me know and i'll do my best to expand or provide any additional information!
toString method joins the array and returns one string containing each array element separated by commas. So you lose the array information.
I usually did something like this with adding multiple inputs:
<form id="form">
<input type="hidden" class="pathArray" name="pathArray[]">
<input type="hidden" class="pathArray" name="pathArray[]">
...
</form>
The idea is that for each value you create a new input. You will have input for Folder 1/File 1.txt, another input for Folder 2/File 2.txt and so on. The final code could look something like this
let picker = document.getElementById('picker');
var pathStructure = [];
var i = 0;
picker.addEventListener('change', e =>
{
for (let file of Array.from(e.target.files))
{
pathStructure[i] = file.webkitRelativePath;
var input = document.createElement("input");
input.type = 'hidden';
input.name = 'pathArray[]';
input.classList.add('pathArray');
document.getElementById("form").appendChild(input);
document.getElementsByClassName('pathArray')[i].value = pathStructure[i].toString();
i++;
};
});
Hope you get the idea.
I'm having issues when trying to access the value of a score that is stored in the localStorage from a variable that is equal to how many questions the user gets right. I thought it would be exactly the same as setting the value but most likely I've done something wrong, and I lack the experience to figure it out..
I Want to display the User's score on the screen's scoreboard where the complete button is. I easily set the score into the localStorage with the setItem(users, score) line, but it seems getItem(score) doesn't work when I want to set displayUser.textContent = getItem(score).
I've tried a lot of different ways, and I always get null. I also noticed every time I submit a new entry to the scoreboard, the key's name keeps the last entries name and stores it on the end.
I'd love to fix this myself, but after making no progress or any leads for 3 hours, I think I might ask for some help. I reused and changed a lot of this code from a class activity in my boot camp so the complete button is just there to remove entries while in development.
Here's all of the relevant JavaScript hopefully
//Variables to Shorten text
var startButton = document.getElementById('startbtn')
var nextButton = document.getElementById('nextbtn')
var finishEarlyButton = document.getElementById('finishEarlyBtn')
var introSection = document.getElementById('intro')
var questionSection = document.getElementById('Question-Section')
var questionElement = document.getElementById('question')
var answerButtons = document.getElementById('Answer-Section')
var scoreboard = document.getElementById('Score-Container')
var userScore = document.getElementById('Score')
var seeScoreBtn = document.getElementById('seeScore')
var restartBtn = document.getElementById('restart')
var finishbtn = document.getElementById('finishbtn')
var userAnswer = ""
var shuffledQuestions, currentQuestionIndex
var score = 0
var userName = document.getElementById('scoreboard-input')
var leaderboard = document.getElementById('leaderboard')
var leaderboardUsers = document.getElementById('leaderboardUsers')
var users = [];
init();
function init() {
var storedUsers = JSON.parse(localStorage.getItem("Users"))
if (storedUsers !== null) {
users = storedUsers;
renderUsers();
}
}
function renderUsers() {
leaderboardUsers.innerHTML = "";
for (var i = 0; i < users.length; i++) {
var user = users[i];
var li = document.createElement("li");
li.textContent = user;
li.setAttribute("data-index", i);
var button = document.createElement("button");
button.textContent = "Complete";
var displayUser = document.createElement("button");
displayUser.textContent = (localStorage.getItem(score));
//displayUser.textContent = "test";
console.log(localStorage.getItem(users.value))
li.appendChild(displayUser);
li.appendChild(button);
leaderboardUsers.appendChild(li);
}
}
function storeUsers() {
//localStorage.setItem("users", JSON.stringify(users));
//localStorage.setItem(JSON.stringify(users), JSON.stringify(score));
localStorage.setItem(users, score);
}
leaderboard.addEventListener("submit", function() {
event.preventDefault();
var userText = userName.value.trim();
var userCorrectAnswers = score.value;
if (userText === "") {
return
}
//users.push(userCorrectAnswers);
users.push(userText);
userName.value = "";
storeUsers()
renderUsers()
console.log
})
leaderboardUsers.addEventListener("click", function(event) {
var element = event.target;
if (element.matches("button") === true) {
var index = element.parentElement.getAttribute("data-index");
users.splice(index, 1);
storeUsers();
renderUsers();
}
})
Let me know if the html or rest of JS is needed!
Well just by looking at the code we can see that you're accessing it via
var storedUsers = JSON.parse(localStorage.getItem("Users"))
and storing it via
localStorage.setItem(users, score);
With the way you're accessing it, you would set it via
localStorage.setItem("Users", JSON.stringify(users));
It is case-sensitive, which is probably why your attempt of using the key users didn't work in your first comment under your storeUsers function.
This is a lot of code to sift through but setting and getting items requires string key-names and stringified values:
localStorage.setItem('users', JSON.stringify(score))
JSON.parse(localStorage.getItem('users'))
This way you should have the same data before and after setting to localStorage.
You are not using localStorage setItem correctly.
localStorage.setItem(users, score);
Both arguments to setItem() must be strings, with the first argument a key, and the second argument the value to store. Your first argument is an array (the data type of your second argument is unclear).
Typical value of a setItem first argument: 'usersScores'.
localStorage.setItem('usersScores', JSON.stringify(score));
Note the use of JSON.stringify() to convert score to a string, because localStorage only stores data in string form.
You are also not using getItem correctly:
localStorage.getItem(score)
getItem must be called with the key used in setItem:
localStorage.getItem('userScores')
And since score was saved as a string, you need to convert it back when you read it from localStorage:
score = JSON.parse(localStorage.getItem('userScores'))
How to use localStorage is explained clearly in MDN web docs Using the Web Storage API.
I have tried everything and I can not split a PHP variable into two parts so I can insert them into two input fields. I have read numerous topics here and I don't see the problem...
This peace of code gives me a result that php variable is inserted into a wanted filed.
Lets say the PHP variable is data1-data2:
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
document.hiderad.opis.value = str.value;
}
Code above inserted data1-data2 into wanted HTML input.
And soon as i try to split it i get undefined warning. I have tried 7 different things to approach this problem so i want even list all the versions I tried. Can someone please help?
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
var array = str.toString().split('-');
a = array[0], b = array[1];
document.hiderad.opis.value = a.value;
document.hiderad.iznos.value = b.value;
}
Code above gives me b undefined if i remove last line i get a undefined.
You shouldn't be using a.value and b.value, that's for getting the value of an input field, not a string. You should use that to get the value of the selectstate input.
Also, always declare local variables unless you have a specific reason to assign global variables.
function updateText() {
var str = document.hiderad.selectstate;
var array = str.value.split('-');
var a = array[0], b = array[1];
document.hiderad.opis.value = a;
document.hiderad.iznos.value = b;
}
I’m trying to create some simple javascript to autofill a webpage.
I’d like to modify the following for use with a specific elementid for the username ‘password_username’ and password ‘password_password’
var result = [];
// Get all links from the page need to change to specific for username
var elements = document.querySelectorAll("input");
for (let element of elements) {
element.value = "username";
}
// Get all links from the page need to change to specific for password
var elements = document.querySelectorAll("input");
for (let element of elements) {
element.value = "password";
}
// Call completion to finish
completion(result) `
I’ve only just started to learn code and have very basic javascript knowledge, any help is appreciated!
Cheers,
Mat
Not entirely sure if this will work as imagined as I can't test it out right now, but give it a shot:
const usernameElements = document.querySelectorAll(`input[type="text"]`);
const passwordElements = document.querySelectorAll(`input[type="password"]`);
usernameElements.forEach(username => username.value = "the user name");
passwordElements.forEach(password => password.value = "the password");
It selects the input fields according to the type (text/password) and adds the value to them. Now I am not entirely sure if this that you posted is part of a bigger script, but this might do the trick that you need. You'd need to make the username and password variables to dynamically load, if you want different usernames and passwords, otherwise this adds the values that you give it, like for example username.value = "testing username" and password.value = "testing password" . Cheers.
Hope I understood your question correctly.
To select a specific field by id and set a value to it, you may use document.querySelector("#the_id").value = "the_value";
If you have an object with {id: value} structure, you can process it in a loop:
const creds = {
id1: 'val1',
id2: 'val2' // ...
};
for (const [id, val] of Object.entries(creds)) {
document.querySelector(`#${id}`).value = val;
}
Please clarify if I did not understand what you need, I'll be glad to help.