I am trying to set the value of an HTML input field (type number) whenever a combo box value id changed using JavaScript (onchange).
I do this on two different HTML pages.
One the first page, the JavaScript codes works of which the following is an extract (NOTE: variable hc is being set correctly as a number)
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
var hc = this.responseText;
hc = hc.replace(/[^0-9]/g, "");
document.getElementById("HC").value = hc;
} else {
alert('failure!');
}
}
};
However, If I use similar code for ElementID HCID I get an error "Uncaught TypeError: Cannot set property 'value' of null" for the line
document.getElementById("HCID").value = hc;
. Again the value for hc is being set correctly.
If I remove the "" around the element ID then the code works. Change code as follows
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
var hc = this.responseText;
hc = hc.replace(/[^0-9]/g, "");
document.getElementById(HCID).value = hc;
} else {
alert('failure!');
}
}
};
Why is this happening?
As you may gather I am new to JavaScript.
What I have tried:
As can be gather by the question I have tried adding "" or removing them