Please help to figure out, why my code doesn't work

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.

  1. I’ve created HTML form with 2 inputs and 1 button.
  2. I got all elements using DOM via id
  3. 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.
  4. 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');
  }
});

The button is placed inside the form tag ?

1 Like

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');
  }
});
1 Like

Good old HTML can do that natively, have you explored this possibility?

Hello @alexvillhen yes I placed unput and button inside of the form. Thanks for a help.

1 Like

Hello @Marmiz . I want to learn how to work with DOM and need to learn how it could be done. Thanks for a help!

@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.

1 Like

Glad it worked! Keep going, you’re in a good path :grin:

1 Like