Click here to Skip to main content
15,038,467 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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;
//                    loads handicap to player handicap id
                } else {
                    // not OK
                    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;
            // loads handicap to player handicap id
        } else {
            // not OK
            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
Posted
Updated 30-May-19 6:13am

1 solution

Without the HTML of the page having the problem I cannot be certain, but; it sounds like the page in question does not have an element with an ID="HCID"

The first thing I would do is go to the page, view-source, and search for HCID to see if it truly is there and in what context it appears
   
Comments
Dave the Golfer 30-May-19 12:46pm
   
Thanks for that . I have realised that HCID is a variable that is set to the ID so does not require "".
earlier JavaScript sets var HCID = 'PHC'+i;
The element ids are PHC1 PHC2 etc

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900