'Using Javascript to store an HTML form
I am trying to have a form submitted, and store elements of it as variables in Javascript. Here's the HTML:
<form id ="form" onSubmit="JavaScript:ScriptJS()">
<label for ="zip">ZipCode: </label>
<br/>
<input type="number" name = "zip" id = "zip">
<br/>
<label for ="type">Cancer Type: </label>
<select name ="type" id = "ctype">
<option value ="a">A</option>
<option value ="b">B</option>
<option value ="c">C</option>
</select>
<br/>
<input type="submit" id ="submit">
</form>
And here's the Javascript that I'm trying to use:
function Submit(){
const zipCode = document.getElementsById("zip");
const cType = document.getElementsById("ctype");
}
console.log(ZipCode);
console.log(CType);
VS code is telling me that the constants are not defined. Help anyone? Thank you
Solution 1:[1]
There are a variety of things wrong here...
- The function is called
getElementById, notgetElementsById - You're defining the constants in the function, so you can only reference them in the function.
- You have to reference them by the same name you used when defining them.
- You never invoke the
Submit()function. - If the form is reloading the page, everything client-side is lost anyway.
Correcting each one...
function Submit(e){
e.preventDefault(); // 5
const zipCode = document.getElementById("zip"); // 1
const cType = document.getElementById("ctype"); // 1
console.log(zipCode); // 2 & 3
console.log(cType); // 2 & 3
}
<form id ="form" onsubmit="Submit(event)"> <!-- 4 -->
<label for ="zip">ZipCode: </label>
<br/>
<input type="number" name = "zip" id = "zip">
<br/>
<label for ="type">Cancer Type: </label>
<select name ="type" id = "ctype">
<option value ="a">A</option>
<option value ="b">B</option>
<option value ="c">C</option>
</select>
<br/>
<input type="submit" id ="submit">
</form>
Of course, preventing the form from submitting will do exactly that. So it's not entirely clear what the end goal is here. So I suppose that change is optional, as you'll still see what's logged to the console if the page reloads as long as your debugging tools are configured to retain the console history.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David |
