Question: How can I simplify this code so it doesn't repeat for pinCode1 and pinCode2? (the code in bold format) window.onload = () => { let
How can I simplify this code so it doesn't repeat for pinCode1 and pinCode2? (the code in bold format)
window.onload = () => { let pinCode1 = document.getElementById("pincode1"); // Get form elements let pinCode2 = document.getElementById("pincode2"); pinCode1.addEventListener("blur", (event) => { if ((isNaN(pinCode1.value)) || (pinCode1.value.length < 4)) { // Check first part of pincode on blur to see if a four digit number has been entered. pinCode1.focus(); // Bad entry. Force retry, using 'focus' method. pinCode1.style.borderColor = "#F00000"; // Alert user by highlighting bad entry } else { pinCode2.focus(); // Good entry. Move to next part of pincode using 'focus' method. pinCode1.style.borderColor = "#008000"; // Show good entry } }, false); pinCode2.addEventListener("blur", (event) => { // As above for second part of pincode if ((isNaN(pinCode2.value)) || (pinCode2.value.length < 4)) { pinCode2.focus(); pinCode2.style.borderColor = "#F00000"; } else { pinCode2.style.borderColor = "#008000"; } }, false); let myForm = document.getElementById("login"); myForm.addEventListener("submit", (event) => { event.preventDefault(); // Stop the form from submitting console.log("Form has been submitted"); // For demo puposes }, false); }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
