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

146
Visualizações
Global variable not working as an input value

I am a JavaScript beginner, I am stuck with a problem regarding variables.

I wrote this code :

var acNo = document.getElementById("ac").value;

function doSomething(){
    alert(acNo);
}

The output is: undefined

But when I did this :

var acNo = 3

The output is 3

Html code : (This is a very big project so that's why I cant share much code, but I am sharing the HTML code related to this script)

<td>A/c</td>
            <td> <input type="number" name="" id="ac"></td>
            <td> <input type="number" name="" id="acHour"></td>

Can you please tell me how can I fix it while keeping the variable global only.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Try defining acNo after the document has fully loaded, or within the function.

Solution 1:

let acNo;

window.onload = () => {
 acNo = document.getElementById("ac").value;
}

function doSomething() {
 alert(acNo);
}

Solution 2:

funtion doSomething() {
    alert(document.getElementById("ac").value)
}
about 4 years ago · Juan Pablo Isaza Relatório

0

A way you can go to check that is by opening the dev tools of your browser and running your document.getElementById in the console.

You will be able to see everything about the element and what properties it has. For example, you might want to check innerHTML instead of value depending on your element type.

about 4 years ago · Juan Pablo Isaza Relatório

0

I think the value is only set in the beginning and not when you run doSomething later. If you want to have the value globally, have a global variable and keep updating it when you call doSomething.

var acNo = document.getElementById("ac").value;

function doSomething(){
acNo = document.getElementById("ac").value;
alert(acNo);
}
about 4 years ago · Juan Pablo Isaza 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