简体   繁体   中英

Capturing the text within an input field

I'm having trouble figuring out what I'm doing wrong in this code. I'm simply trying to set the user's input for username and password and store them in their respective variables. For some reason the variables are always and empty string. Could someone tell me where I'm going wrong?

HTML

<body>
<main>
    <h1>Login Form</h1>
    <form>
        <label for="username">Username:</label>
        <input type="text" name="username" id="username">
        <label for="password">Password:</label>
        <input type="text" name="password" id="password">
        <button id="submitButton" type="button">Submit</button>
    </form>
</main>
<script src="loginPage.js"></script>
</body>

JS

var submitButton = document.getElementById("submitButton");
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var user = {username, password};
console.log(user);

Keep in mind, that the variables will only be populated after a change to the input.

 document.querySelector('input[name:username').addEventListener('change',(e)=>{ var username = e.target.value; } document.querySelector('input[name:password').addEventListener('change',(e)=>{ var password = e.target.value; } 
 <form> <label for="username">Username:</label> <input type="text" name="username" id="username"> <label for="password">Password:</label> <input type="text" name="password" id="password"> </form> 

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