Following is a statement that should run according to me when the HTML page loads.
document.getElementById("name_field").value = "JavaScript";
But this does nothing.If i try to do the same thing the different way :
window.onload = init;
function init() {
document.getElementById("name_field").value = "JavaScript";
}
Then this works fine.
What is wrong with the first script.?
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="valtest.js">
</script>
</head>
<body>
<form>
<label>Enter your name <input type="text" id="name_field" /></label> <br/>
<input type="submit" value="submit" />
</form>
</body>
</html>
Onload runs after the HTML has been rendered in the page. So in your first example the element is not yet available for JavaScript processing.
Most use “document ready”, which means the document has been rendered.
jQuery example: