Turn HTML Form Input into JavaScript Variable
forms, html, javascript, variables
Solution
Accessing HTML input elements from JavaScript
Assuming you don't have other elements with same names, you can access input values from JavaScript by name as follows:
var firstName = document.getElementsByName("firstname")[0].value;
You now have the value from firstname field in JavaScript variable called firstName. Just keep repeating and you got the other input fields too. You can then proceed and wrap these statements to a function and call it when input data changes. For example:
function formChanged() {
var firstName = ...
var lastName = ...
}
Now register this function call to change / keyup events and you have a function that monitors changing form values:
<input type="text" name="firstname" onkeyup="formChanged()" onchange="formChanged()"/>
Problem
I am new to HTML forms and I was wondering how I can easily (or not) change it's input to a JavaScript variable. Here is my code: ``` <head> <title>Begin</title> <link type="text/css" rel="stylesheet" href="begin.css"/> </head> <body> <form action="begin-create-done.html" method="get"> First Name: <input type="text" name="firstname"> <br> Last Name: <input type="text" name="lastname"> <br> <br> New Username: <input type="text" name="user"> <br> Password: <input type="password" name="pass"> <br> Repeat Password: <input type="password" name="rpass"> <input type="submit" value="Submit"> </form> </body> </html> ``` I want each part of the form (e.x. First Name, Last Name, New Username, etc.) to be it's own JavaScript variable. Thank you very much!