I need to implement a feature where a button is disabled until all input fields on the page are filled. The challenge is that I must achieve this using only JavaScript without converting the structure to a form as it would interfere with other aspects of the code. Currently, the button turns enable when some inputs are filled (even just one), but if all inputs are completed, the button disables again. It also remains disabled when no inputs have been filled. My goal is to enforce the requirement for all inputs to be filled before enabling the button, ensuring that users cannot submit the form empty or with partially completed fields.
The JavaScript code below demonstrates how input validation is achieved:
document.addEventListener('DOMContentLoaded', function(){
const required = document.querySelectorAll('.input');
function checkSubmit(button){
let isValid = true;
for(let i = 0; i <required.length; i++){
isValid = isValid && !!required[i].value;
console.log("is enabled");
}
button.disabled = isValid;
console.log("is disabled");
}
function inputHandler(button){
return function(){
checkSubmit(button);
};
}
// Get all quiz buttons enableChecking();
const quizButton = document.querySelectorAll('.quiz_button');
for (const button of quizButton){
button.disabled = true;
for(let i = 0; i <required.length; i++){
required[i].addEventListener("input", inputHandler(button));
}
button.addEventListener('click', (event) =>
check_quiz(event.target.id));
}
});