简体   繁体   中英

Getting data from the HTML form into JavaScript

I am trying to get the values from the form inputs once you click submit into variables in JavaScript.

However I don't seem to be having much luck as the console log just shows the variables as empty.

HTML

<html>
<head>
    <meta charset="UTF-8">
    <title>Registration</title>
</head>
<body>
<fieldset><legend>Registration</legend>
<form action="#" method="post" id="theForm">
    <label for="username">Username<input type="text" name="username" id="username"></label>
    <label for="name">Name<input type="text" name="name" id="name"></label>
    <label for="email">Email<input type="email" name="email" id="email"></label>
    <label for="password">Password<input type="password" name="password" id="password"></label>
    <label for="age">Age<input type="number" name="age" id="age"></label>
    <input type="hidden" name="unique" id="unique">
    <input type="submit" value="Register!" id="submit">
</form>
</fieldset>

<div id="output"></div>

<script src="js/process.js"></script>    

</body>

</html>

JS

var output = document.getElementById('output');

function addUser() {
    'use strict';
    var username = document.getElementById('username');
    var name = document.getElementById('name');
    var email = document.getElementById('email');
    var password = document.getElementById('password');
    var age = document.getElementById('age');
    console.log(username.value);
    console.log(name.value);
    console.log(password.value);
}

// Initial setup:
function init() {
    'use strict';
    document.getElementById('theForm').onsubmit = addUser();
} // End of init() function.
//On window load call init function
window.onload = init;

EDIT It was because I needed to remove () on addUser and also add return false to the addUser function at the bottom.

In

function init() {
    'use strict';
    document.getElementById('theForm').onsubmit = addUser();
}

This will set the onsubmit equal to undefined because addUser returns nothing. To get the function addUser as the onsubmit function use this instead.

function init() {
    'use strict';
    document.getElementById('theForm').onsubmit = addUser;
}

You are trying to pass the function itself not the return of it.

Also, when I'm making functions that will be passed or set, I find it more reasonable to write them like this:

var addUser = function(){
    ...
}

In order to make your function working, you might want to do this:

   function init() {
        'use strict';
        document.getElementById('theForm').onsubmit = function () { addUser(); }
    } 

You can refer to the post below for further explanation:

Timing of button.onclick execution

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM