Bob
Bob

Reputation: 97

How can I apply the same event listener used for all elements on form submission?

Here's my sample JS code:

function createListener(input) {
  return (e)=> {
    const el=e.target;
    const inputValue=e.target.value;
    const validator=inputCheck(input)
    const valid=validator(inputValue);
    borderHighlight(valid, el)
  }
}

inputs.forEach(input=> {
  input.addEventListener("input", createListener(input))
})


function borderHighlight(valid, el) {
  (valid)? el.style.border='2px solid green':el.style.border='2px solid red'
}

myForm.addEventListener('submit', (e)=> {
  e.preventDefault()
  inputs.forEach(input=> {
    createListener(input)
  })
})

The input event listener on each element is perfect for what it does. It gives live error messages as the user inputs. But I want that function to do the same thing when the user submits the form as well (on the submit event attached to the form element)? How can I implement that functionality in my code?

Upvotes: 0

Views: 932

Answers (2)

Barmar
Barmar

Reputation: 781503

Put the validation code in a named function, so you can call it from both event listeners.

function validate_input(el) {
    const inputValue=el.value;
    const validator=inputCheck(el)
    if (validator) {
        const valid= validator(inputValue);
        borderHighlight(valid, el);
    }
}

function createListener(input) {
    return e => validate_input(input);
}

inputs.forEach(input=> {
  input.addEventListener("input", createListener(input))
})


function borderHighlight(valid, el) {
  (valid)? el.style.border='2px solid green':el.style.border='2px solid red'
}

myform.addEventListener('submit', (e) => {
  e.preventDefault();
  inputs.forEach(input => validate_input(input));
});

Upvotes: 1

Teemu
Teemu

Reputation: 23406

Change the form submit listener a bit. Call the function returned from createListener and pass a fake event object: {target: input}.

myForm.addEventListener('submit', (e)=> {
  e.preventDefault()
  inputs.forEach(input=> {
    createListener(input)({target: input});
  })
});

This way you don't need to change anything within createListener.

Upvotes: 1

Related Questions