javascriptformssubmitaddeventlistener

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?


Solution

  • 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));
    });