I am doing a rock, paper and scissors exercise and I just added a form with an input text and an input button to store the user name and show it on the DOM.
The thing is, with console.log($userName.value) it will only show me the value when it is on the box, if I delete it or submit it will show nothing or undefined, I added the form.submit() because I want the user to send the text on the input and then let the input empty (I also tried to set the .value to an empty string but it won't work either way.
I added it to a variable with innerHTML to show it on the DOM but if I clear the input it will show undefined.
I am probably skipping a few steps but I don't know how to get to it. Any guidance would be appreciated.
let $userForm = document.querySelector('#user-form');
let $userName = document.querySelector('#user-name');
$userForm.addEventListener('submit', (event) => {
const $userName = document.querySelector('#user-name').value;
console.log($userName.value);
$userForm.submit();
})
<form id ="user-form">
<input type="text" id="user-name" placeholder="Please, insert your name..">
<input type="submit" id="submit-name" value="Enviar">
</form>
Thanks a lot.
CodePudding user response:
Use a different variable in the function. There you can use the $userName
global variable to access the HTML element, and .value
to get its value.
let $userForm = document.querySelector('#user-form');
let $userName = document.querySelector('#user-name');
$userForm.addEventListener('submit', (event) => {
const name = $userName.value;
console.log(name);
$userForm.submit();
})
<form id="user-form">
<input type="text" id="user-name" placeholder="Please, insert your name..">
<input type="submit" id="submit-name" value="Enviar">
</form>
CodePudding user response:
Not sure if your form will be sent, at least I don't think so.
If you want to display the name of the user or even store this data somewhere to display it somewhere you can do it this way
<form id ="user-form">
<input type="text" id="user-name" placeholder="Please, insert your name.." onchange="registerInput(this);">
<input type="submit" id="submit-name" value="Enviar">
</form>
<h1>
</h1>
let $userForm = document.querySelector('#user-form');
let $userName = document.querySelector('#user-name');
let inputValue = ""
function registerInput(e)
{
const {value} = e;
inputValue = value;
}
$userForm.addEventListener('submit', (event) => {
event.preventDefault();
document.querySelector('h1').innerText = 'Hello : ' inputValue;
})
Link : https://jsfiddle.net/38egvn2q/1/
Note : You can also clear the input inside the submit event function
Note² : You can also store the variable inside the window object
For example :
window.inputValue = 'something'
Or you can also use the (recommended) localStorage or the sessionStorage for future use