How to capture a text or number that has been entered into a text box in JS

1

To the user to enter a text or number, how can I capture it and store it in a variable?

I've been testing with:

let captureNumber = document.getElementById("number2").innerHTML;

console.log(captureNumber)
 <input type="number" placeholder="Nivel de Seguridad"  min="65" max="90" id="number2">

What I try to do there is that the user selects a number to be captured and that number will be shown in the console.

    
asked by user889 30.05.2018 в 17:34
source

2 answers

2

In your exercise two things are missing, a trigger of the event that will execute the function of capturing the value and actually capture the value:

In this case we will use the onchange event that is executed when a form element changes its value.

Once we have detected the change of value we proceed to capture the value, which in capture form elements with .value and not with .innerHTML as you tried to do.

function cambioValor(){
  let captureNumber = document.getElementById("number2").value

  console.log(captureNumber)
}
<input type="number" placeholder="Nivel de Seguridad"  min="65" max="90" id="number2" onchange="cambioValor();">
    
answered by 30.05.2018 / 17:38
source
0

You have many options, I put two of them:

With OnKeyPress

const $number2 = document.getElementById("number2");
$number2.onkeydown = function(ev){
  console.log("tecla ingresada que debo validar" , ev.key)
  console.log("valor antes de la validacion" , this.value)
};
<input type="number" placeholder="Nivel de Seguridad"  min="65" max="90" id="number2">

With Listeners

const $number2 = document.getElementById("number2");
$number2.addEventListener('keydown', function(ev) {
   console.log("tecla ingresada que debo validar" , ev.key)
  console.log("valor antes de la validacion" , this.value)
 })
<input type="number" placeholder="Nivel de Seguridad"  min="65" max="90" id="number2">
    
answered by 30.05.2018 в 17:43