Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn HTML Form Input into JavaScript Variable

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!

like image 735
user3697292 Avatar asked Jun 01 '14 17:06

user3697292


People also ask

How do you input variables in JavaScript?

In JavaScript, we use the prompt() function to ask the user for input. As a parameter, we input the text we want to display to the user. Once the user presses “ok,” the input value is returned. We typically store user input in a variable so that we can use the information in our program.

Can JavaScript handle forms?

With JavaScript at your side, you can process simple forms without invoking the server. And when submitting the form to a CGI program is necessary, you can have JavaScript take care of all the preliminary requirements, such as validating input to ensure that the user has dotted every i.

Can I use JavaScript variable in HTML?

You cannot use js variables inside html. To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html.


1 Answers

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()"/>
like image 56
jsalonen Avatar answered Sep 30 '22 23:09

jsalonen