I have an input text for userNameValue and userScoreValue variable which takes in the value of an input.
In the object, 'game' , I have a method that pushes the DOM values of the userNameValue and userScoreValue into an object inside of the empty array, 'allUsers'
When its time for the submit event listener click, the key-value pairs are empty, but have successfully pushes into the allUsers array.
How can I make it so that when a user puts in their name, score and submit the button, the key-value pair will not be an empty string (' ').
'use strict';
const userNameValue = document.querySelector('.name').value;
const userScoreValue = document.querySelector('.score').value;
const submit = document.querySelector('.submit');
const game = {
allUsers: [],
addPlayers(){
this.allUsers.push({userNameValue, userScoreValue});
console.log(this.allUsers);
}
}
submit.addEventListener('click', game.addPlayers.bind(game));
CodePudding user response:
The issue is that you are getting the value of the inputs when the script is first loaded, rather than when the button is clicked. To fix this, you should move the code that gets the input values into the event listener function.
submit.addEventListener('click', () => {
const userNameValue = document.querySelector('.name').value;
const userScoreValue = document.querySelector('.score').value;
game.addPlayers({userNameValue, userScoreValue});
});
And update the function addPlayers
to take an object parameter, instead of using the global variable.
const game = {
allUsers: [],
addPlayers(user){
this.allUsers.push(user);
console.log(this.allUsers);
}
}