Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!