Question:
I am doing a project in which when entering a data in the input it should appear at least in the console.log() so that I can work with it later. In my case I enter a text in an input and pressing enter should show the value of my input in the console.log() but it does not happen. what can i be doing wrong?
let nom = document.getElementById("Nombre");
const valor = document.getElementById("valor").value;
document.addEventListener("keyup", (event) => {
if (event.keyCode === 13) {
event.preventDefault();
console.log(valor);
}
});
<form>
<label for="nombre">Nombre: </label>
<input type="text" id="valor"/>
</form>
The result of the input in the console.log() is always empty
Answer:
let nom = document.getElementById("Nombre");
document.addEventListener("keyup", (event) => {
if (event.keyCode === 13) {
const valor = document.getElementById("valor").value;
event.preventDefault();
console.log(valor);
}
});
<label for="nombre">Nombre: </label>
<input type="text" id="valor"/>
You are defining a constant, it takes the value of the input when the page loads, therefore it will be empty, you must define the constant at the moment the event occurs, it will be valid only for the event (after the event block already cannot be obtained), so that we will obtain the current value and not the initial value (the one obtained when the page loads)
Also you have to add a preventDefault
so that the page does not reload since you are using a <form>
document.querySelector("form").addEventListener("submit", e => {e.preventDefault();});
Since there is no submit
button in the <form>
, the page assumes that the submit
will be done with the <input>
You can combine it with the form
, resulting:
let nom = document.getElementById("Nombre");
document.querySelector("form").addEventListener("submit", e => {e.preventDefault();});
document.addEventListener("keyup", (event) => {
if (event.keyCode === 13) {
const valor = document.getElementById("valor").value;
event.preventDefault();
console.log(valor);
}
});
<form>
<label for="nombre">Nombre: </label>
<input type="text" id="valor"/>
</form>