What specific syntax must be changed in the code below in order for the value for firstname to be successfully transferred into the index.js logic from the index.html form?
ERROR MESSAGE:
Currently, the value for firstname is being read as null by the const firstnameInput = document.querySelector("input[firstname='firstname']"); line of index.js.
The error given in the Developer Tools tab of my browser is:
caught TypeError: Cannot set properties of null (setting 'isValid')
at index.js:4:24
The line in index.js referenced by the error message is:
firstnameInput.isValid = () => !!firstnameInput.value;
But as you can see from the code below, the value of firstnameInput is first supposed to be brought in by the const firstnameInput = document.querySelector("input[firstname='firstname']"); line.
CODE FOR index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Validation</title>
<link rel="stylesheet" href="style.css" />
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700&display=swap"
rel="stylesheet"
/>
</head>
<body>
<div class="contact-banner">
<h1>Form Name</h1>
</div>
<form name="contact-form">
<div class="form-control">
<label>First Name</label>
<input name="firstname"
placeholder="First Name"
id="firstname-input" />
<div class="error hide">First Name is required</div>
</div>
<hr />
<button type="submit" id="submit">SUBMIT FORM</button>
<div id="success" class="success">Successfully submitted.</div>
<div id="fail" class="fail">Submission error.</div>
</form>
<script src="index.js"></script>
<script src="contact.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</body>
</html>
CODE FOR index.js:
const form = document.querySelector("form[name='contact-form']");
const firstnameInput = document.querySelector("input[firstname='firstname']");
firstnameInput.isValid = () => !!firstnameInput.value;
const inputFields = [firstnameInput];
let shouldValidate = false;
let isFormValid = false;
const validateInputs = () => {
if (!shouldValidate) return;
isFormValid = true;
inputFields.forEach((input) => {
input.classList.remove("invalid");
input.nextElementSibling.classList.add("hide");
if (!input.isValid()) {
input.classList.add("invalid");
isFormValid = false;
input.nextElementSibling.classList.remove("hide");
}
});
};
form.addEventListener("submit", (e) => {
e.preventDefault();
shouldValidate = true;
validateInputs();
if (isFormValid) {
// TODO: DO AJAX REQUEST
}
});
inputFields.forEach((input) => input.addEventListener("input", validateInputs));
>Solution :
Should be
input[name='firstname']
instead of
input[firstname='firstname']