You are most-likely attempting to run that JavaScript code BEFORE the HTML element has been parsed into the DOM.
When the JavaScript runs, the input
element hasn't been loaded into memory yet, so your document.getElementById()
returns null
and then you attempt to get the value
of that (hence your error message).
You can either move your script to the end of the body
element or you can set up an event handler for when the page is loaded.
Scenario #1 (Move the script so that it occurs AFTER all HTML)
<html>
<head>
</head>
<body>
<input type="text" id="callno" value="3333">
<script>
(function(){
// It's best to just cache DOM refrences, not actual properties
// so that you can reuse the reference for multiple reasons
// Don't do this:
//var phoneNumber = document.getElementById("callno").value;
// Do this:
var phoneElement = document.getElementById("callno");
// We'll declare a variable outside of the callback function
// that will hold the actual value later.
// This way, you can use the variable at any point you may need to.
var phoneNumber = null
// Now, we can do many things with that element.
// In this case, we'll wire it up to an input event
// handling function that fires whenever the element
// receives input
phoneElement.addEventListener("input", function(){
// And then we can use it to get its stored value
// It's important that we update the variable when
// the textbox value changes.
phoneNumber = phoneElement.value
console.log(phoneNumber);
});
}());
</script>
</body>
</html>
Scenario #2 (Set up an event handler that waits until the page is ready)
<html>
<head>
<script>
// Wait until the window has parsed all the HTML elements
// before running its callback function:
window.addEventListener("DOMContentLoaded", function(){
// This function won't execute until all the HTML elements
// have been read into memory. By now, the input element
// we need is ready to be read.
// It's best to just cache DOM refrences, not actual properties
// so that you can reuse the reference for multiple reasons
// Don't do this:
//var phoneNumber = document.getElementById("callno").value;
// Do this:
var phoneElement = document.getElementById("callno");
// We'll declare a variable that will hold the actual value
// This way, you can use the variable at any point you may need to.
// If we only set the value here though, it won't be updated when
// the value changes.
var phoneNumber = phoneElement.value;
// Now, we can do many things with that element.
// In this case, we'll wire it up to an input event
// handling function that fires whenever the element
// receives input
phoneElement.addEventListener("input", function(){
// And then we can use it to get its stored value
// It's important that we update the variable when
// the textbox value changes.
phoneNumber = phoneElement.value
console.log(phoneNumber);
});
});
</script>
</head>
<body>
<input type="text" id="callno" value="3333">
</body>
</html>