Search code examples
javascripthtmlgetelementbyid

getElementById.value is not working ERROR: form1.html:10 Uncaught ReferenceError: f1 is not defined at HTMLButtonElement.onclick (form1.html:10)


I've been trying a lot to run this code, but unfortunately it didn't seem to work; It says

Uncaught TypeError: Cannot read property value of null

I noticed that getElementById().value is the culprit but it prints results without error when I run another file on the same browser(CHROME, IE, FIREFOX) which was pre executed on another computer already.

And also getElementById used to work perfectly a few months ago.

Please help me. This is frustrating! Thanks in advance

function f1()
{
	document.write("Hello")

	var cname = document.getElementById('user_name').value;
	document.write(cname);
}
<!DOCTYPE html>
<html>
<head>
	<title>Welcome!</title>
	
</head>
<body>
	
	Enter Name: <input id="user_name" type="text"  /><br/>
	<button onclick="f1()">Click</button>
	
	<script type="text/javascript" src="form1.js"></script>
</body>
</html>


Solution

  • After printing hello your page DOM is reloaded where textfield is not present that's why it's not working try below one code

    function f1()
    {
        var cname = document.getElementById("user_name").value;
        document.write("Hello "+cname);
    }