Hello everyone. Thanks in advance for your help and time! I’ve got a task to check if a HTML form is complete , or not using DOM events, when button is pressed.
I’ve created HTML form with 2 inputs and 1 button.
I got all elements using DOM via id
Then I tried to add event listener to the button and used if statement inside of eventListener to check forms, but code doesn’t work.
I need to use alert() if form is complete or not inside of html
Below is the code
let checkForm = document.getElementById('form');
let checkForm1 = document.getElementById('form1');
let btn = document.getElementById('checkFill');
btn.addEventListener('click', () => {
if (checkForm.length > 0 && checkForm1 > 0) {
alert('Forms are completed');
} else if (checkForm.length === 0 && checkForm1 === 0) {
alert('PLease complete a form');
}
});
I think you should use the value property to check the length of the input, also i think it’d be better if you use and or ( || ) instead of && in the else if condition. like this:
let checkForm = document.getElementById('form');
let checkForm1 = document.getElementById('form1');
let btn = document.getElementById('checkFill');
btn.addEventListener('click', () => {
if (checkForm.value.length > 0 && checkForm1.value.length > 0) {
alert('Forms are completed');
} else if (checkForm.value.length === 0 || checkForm1.value.length === 0) {
alert('PLease complete a form');
}
});
@alexvillhen Thanks a lot for your time and help. Now everything works as it should! I’ve spent one hour for this simple task. I’m new to programming and JS, hope to get good knowledge to become frontend web developer.