#Submit Button with EventListener

8 messages · Page 1 of 1 (latest)

gleaming mulch
#

Hi, I created a form with required inputs and a submit button that works fine if nothing is is typed in the input area.

But when I add an eventlistener to the that same button, the required condition of the inputs seems to be ignored and it goes ahead to execute the function of the eventlistener even if nothing is typed in the input.

Anybody knows how to solve this?

supple shell
gleaming mulch
# supple shell Hi Omar!! Could you share your scrim? 😊

Hi, here is the form in HTML which works fine

<form>

  <input type="text" placeholder="Enter your name" name="name" required>

  <button type="submit" id="pay-btn">Pay</button>

</form>

And the eventListener in JS:

const payBtn = document.getElementById("pay-btn");

payBtn.addEventListener("click", function () {
  console.log("clicked")
});

So without the JS code, the required condition of the inputs works. but when I add the eventListener, is executes the function when I click even if nothing is typed.

How do I make sure the function of the event listener doesn't execute f the input fields are empty.

oblique sail
#

I believe the solution here may be to listen to the 'submit' event of the form instead of the 'click' event of the button...

gleaming mulch
oblique sail
#

No - you need to add the event to the form not the button... like this:

const formEl = document.querySelector('form');
const btnEl = document.querySelector('#pay-btn');

formEl.addEventListener('submit', (e) => {
  e.preventDefault();
  console.log('form submit');
})

btnEl.addEventListener('click', () => {
  console.log('btn click');
})
#

The button click event fires every time you click the button even if the form isn't valid... The submit event however will only fire when the form passes validation.