Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
assign the value of `input ` to a variable but return blank in JS

I want to assign the value of input to a variable in Javascript, but I am not sure why the value of input is always blank.

Here is an example:

let input = document.getElementById('input').value
let val = 'not'

function check() {
  //console.log(document.getElementById('input').value) will work
  console.log(typeof input)
  console.log(input)

}
<input id='input' type='text'>
<button onclick='check()'>Check</button>

The input value is blank (nothing), but the typeof input is string.

If I use document.getElementById('input').value, this will totally work which will display the value of input sucessfully.

Could anyone explain me a little bit why I assign it to a variable won't work?

Thanks for any responds!

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Variable assignment val = 'not' takes place at the first time page load. When you need to assign dynamic value, like on a button click, you need an event handling mechanism (In your case, a click event). You are calling a function upon click, but not assigning any value to your variable there. Make assignment inside function like:

function check() {
  val = document.getElementById('input').value
  console.log(val)
}
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda