I have a form. I want to only allow form submit if the user checks precisely 4 out of 8 available checkboxes; and once the user checks 4 checkboxes I want to disable the remaining unchecked ones.
Should I add a hook to the click
event? Or maybe the input
event? Or perhaps the change
event?
I'm overwhelemed by the amount of events that seem to duplicate each other's functionality.
I'm also confused by the documentation.
For
<input>
elements withtype=checkbox
ortype=radio
, theinput
event should fire whenever a user toggles the control, per the HTML5 specification. However, historically this has not always been the case. Check compatibility, or use thechange
event instead for elements of these types.
Unlike the
input
event, thechange
event is not necessarily fired for each alteration to an element'svalue
.
And below:
Depending on the kind of element being changed and the way the user interacts with the element, the
change
event fires at a different moment:
- When the element is
:checked
(by clicking or using the keyboard) for<input type="radio">
and<input type="checkbox">
;
An element receives a
click
event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.
Practice:
The below JS fiddle seems to hint that all 3 events are equivalent. Clicking the checkbox, clicking the label, focusing the checkbox and pressing space on keyboard seem to all fire all three events.
const checkbox = document.querySelector('input[type=checkbox]');
for (const event of ['input', 'click', 'change']) {
checkbox.addEventListener(event, () => {
log.textContent = `${event}\n${log.textContent}`
})
}
<label>Toggle <input type="checkbox" name="" id="">
</label>
<pre id="log"></pre>
As per the docs change
and input
seem equivalent; click
does not seem equivalent to the other 3 as per the docs but in practice it seems equivalent.
Do we really have 3 events that duplicate each other's functionality? Does it matter in any way which event I use?
Or am I missing something?
Aucun commentaire:
Enregistrer un commentaire