rmcg.dev/projects/FrontendMentor/newbie/intro-component-with-signup.../js/script.js

49 lines
1.6 KiB
JavaScript
Raw Normal View History

2022-09-28 22:06:27 +02:00
"use strict";
2022-09-28 22:06:27 +02:00
const form = document.getElementById("details-form");
const inputs = document.querySelectorAll("input");
2022-09-28 22:06:27 +02:00
for (const input of inputs) {
// console.log(`${input.id} getting focus listener`)
input.addEventListener("focus", inputFocused, false);
}
form.addEventListener("submit", checkFormValidity, false);
2022-09-28 22:06:27 +02:00
/**
* @param {Event} event
*/
function checkFormValidity(event) {
if (form.checkValidity() === false) {
event.preventDefault();
const invalids = form.querySelectorAll(":invalid");
for (const input of invalids) {
// console.log(`${input.id} is invalid`);
// console.log(`${input.id} msg ${input.validationMessage}`);
// get the relevant error message element, using id of the input
let errorSection = document.getElementById(
`errorMessage-${input.id}`
);
2022-09-28 22:06:27 +02:00
// console.log(`ES: ${errorSection}, ${typeof (errorSection)} id: ${errorSection.id}`);
errorSection.hidden = false;
input.classList.add("error-highlight");
2022-09-28 22:06:27 +02:00
}
}
}
2022-09-28 22:06:27 +02:00
// When an input has focus I remove the error state,
// I could more ideally check if the class is in the classlist,
// and attribute hidden was false
function inputFocused(event) {
/**
* Just for VS Code intellisense
*
* @type {HTMLInputElement}
*/
2022-09-28 22:06:27 +02:00
const input = event.currentTarget;
if (input.classList.contains("error-highlight")) {
input.classList.remove("error-highlight");
let errorSection = document.getElementById(`errorMessage-${input.id}`);
errorSection.hidden = true;
}
}