Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda