最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Invalid eventListener for forms - Stack Overflow

matteradmin1PV0评论

I'm trying to catch the invalid event for forms, but it doesn't seem to happen?

For my use case, I need to have the listener on the form (for asynchronous form validation). So attaching the listener to individual inputs is not an option for me.

According to the spec, forms should fire an invalid event when some of the input is invalid.

.html#client-side-form-validation

I'm trying to catch the invalid event for forms, but it doesn't seem to happen?

https://codepen.io/MartinMuzatko/pen/VzWwxG?editors=1010

For my use case, I need to have the listener on the form (for asynchronous form validation). So attaching the listener to individual inputs is not an option for me.

According to the spec, forms should fire an invalid event when some of the input is invalid.

https://www.w3/TR/html5/forms.html#client-side-form-validation

Share Improve this question asked Aug 10, 2017 at 8:40 Martin MuzatkoMartin Muzatko 3265 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

The 'invalid' event is not "bubbled" . It fires on the specific input element which is invalid and won't bubble up to the form element. You need to attach the listener on the input element.

var input = document.querySelector('form input')

input.addEventListener('invalid', (e)=>{
    console.log('invalid')
});

Updated pen: https://codepen.io/theLufenk/pen/WEONBw?editors=1010

Or if you want to catch the event at form level, you will have to use event capturing.

var form = document.querySelector('form')

form.addEventListener('invalid', (e)=>{
    console.log('invalid')
},true)

Update Pen: https://codepen.io/theLufenk/pen/Ojgmxz?editors=1011

Post a comment

comment list (0)

  1. No comments so far