I am trying to get my code to check if the value submitted in "username" already exist in "usernames" list. If it does, would like to have the message displayed and if it does not, add that value to the "usernames" list and submit form.
Don't understand why my code doesn't work. Please see below:
HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Validating Form Data</title>
<link rel="stylesheet" href="index.css" type="text/css">
</head>
<body>
<h3>Register your account:</h3>
<p id="errors"></p>
<form id="registration-form" method="POST" action="https://formdump.codeinstitute.net/">
<div class="username">
<label for="username">Username:</label>
<input id="username" name="username" type="text" required>
</div>
<div class="password">
<label for="password">Password:</label>
<input id="password" name="password" type="password" required>
</div>
<input type="submit">
</form>
<script src="https://code.jquery.com/jquery-3.5.1.slim.js" integrity="sha256-DrT5NfxfbHvMHux31Lkhxg42LY6of8TaYyK50jnxRnM=" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
</html>
CSS
label {
display: block;
}
input {
margin-bottom: 1rem;
}
p {
color: red;
font-weight: bold;
}
JS
let usernames = ["Harry", "Daisy", "Michael", "Sarah", "Sally"];
// Write your code here
let form = document.getElementById("registration-form");
form.addEventListener("submit", handleSubmit);
let errorMsg = document.getElementById("errors");
let uName = form.elements["username"].value;
let abc = usernames.includes(uName);
function handleSubmit(event) {
event.preventDefault();
if (abc) {
errorMsg.innerHTML = `<p>Sorry, the username ${uName} is already in use. Please choose another username.</p>
`;
} else {
usernames.push(uName);
form.submit();
console.log(usernames);
}
}
I tried replacing includes() with indexOf(), but still doesn't work.
let uName = form.elements["username"].value;let abc = usernames.includes(uName);insidehandleSubmit