I was trying to code a basic login web program with javascript when I discovered a problem. I can’t assign value to input function using js. So now I can’t use if else to create a basic login. here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="index.css">
<script src="index.js"></script>
</head>
<html>
<body>
<h1>Login</h1>
<div>
<input type="text" placeholder="Input username" id="username" name="username" class="a47">
<br>
<br>
<input type="text" placeholder="Input password" id="password" name="password" class="a47">
<br>
<button type="button" onclick="login()" class="login">Login</button>
<script>
let username = 'username';
let password = 'password';
function login() {
if (username == a88, password == a89) {
alert("Thành công")
}
else {
alert("Không thành công")
}
}
</script>
</div>
</body>
</html>
please help me
>Solution :
Seems like the input values are not being read from the page. In order to read the input values, you will first be required to grab the input
DOM elements from the page.
The input fields have id
attribute assigned to them which could be used to extract these elements.
<input ... id="username" ...>
<input ... id="password" ...>
You may use query selectors for that:
# Extract username input field
const usernameInputField = document.querySelector('#username')
# Extract password input field
const passwordInputField = document.querySelector('#password')
In the above snippet, document.querySelector
is used to extract any DOM elements from the webpage. This function takes in the CSS selector as a parameter. Here, #username
and #password
are the CSS selectors for username and password fields respectively. The #
sign signifies to select using the DOM element’s ID.
Once we have the input fields, all we are left to do is to get the current values from these fields:
# Get current input value of username input field
const username = usernameInputField.value
# Get current input value of password input field
const password = passwordInputField.value
We use the value
property of the input element to grab the current input value.
Solution:
// Grab the input fields from the page
const usernameInputField = document.querySelector('#username')
const passwordInputField = document.querySelector('#password')
function login() {
// Grab current input values
const username = usernameInputField.value
const password = passwordInputField.value
// The remaining code below stays the same
if (username === a88, password === a89) {
alert("Thành công")
}
else {
alert("Không thành công")
}
}
In the login()
function, we take the current value of the input fields and do the validation as it was handled previously. Note that, we do that inside the function itself to ensure that we have the latest value from the input fields.