I am working on learning form validation when I wanted to test my usage of documents. forms were correct I get an "undefined" error. I have tried using simpler methods like document.getElementById and document.getElementByClassname. I also tried using the different variable declarations such as let, var, and const. When I use the console in developer tools and use the same document. forms in my code, it shows the value that I typed in the input. I also tried putting my javascript code directly into my script tags, instead of using the script tags to link my JS file. I'm completely stumped and can't understand why. Although this should be simple, I am new to this. Any help would be greatly appreciated. Screenshots below...
CodePudding user response:
With the limited information you shared, I reconfigured the application as follows. However, I didn't get any errors. You should share more information to fix the problem.
document.getElementById("getFullNameButton").addEventListener("click", function(e) {
console.log(`Fullname: ${document.forms["myForm"]["fullName"].value}`)
});
<form name="myForm">
<label>Name: </label>
<input type="text" name="fullName" id="fullName">
<button type="button" id="getFullNameButton">Get Full Name</button>
</form>
CodePudding user response:
I wrote out the code from your screenshots so we could demonstrate the problem.
Your JavaScript reference needs to be after the body elements it is trying to reference.
This is your code, with some comments:
<html>
<head>
<!-- some things were omitted //-->
<script src="Assignment3.js"></script>
<!-- THIS IS THE PROBLEM. Move script tag to the end of the body... //-->
</head>
<body>
<form name="myForm">
<input type="text" name="fullName" id="fullName" />
<input type="submit" value="Test" name="testButton" id="testButton" />
</form>
<script type="text/javascript" src="Assignment3.js"></script>
<!-- should be after elements that you want to ref //-->
<!-- please read me earlier comment. //-->
</body>
</html>