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.
CodePudding user response:
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)
}
CodePudding user response:
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.
CodePudding user response:
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);
}