Reputation: 4098
I noticed that the "change" event only fires one event when the element is checked. But does not seem to fire any event when unchecked, or do I miss something?
I would like to do something on "uncheck" but that does never trigger.
Ideally, I do not want to save the inputs in an array and on change check which one is checked or not.
Here is an example, as you can see, "do something" never get’s fired:
document.querySelector("input").addEventListener("change", function(ev) {
console.log(ev.target.checked);
if(!ev.target.checked) console.log("do something");
});
<input type="radio" name="type" checked="checked" value="guest" />
<input type="radio" name="type" value="walk_in" />
This seems so basic… maybe I overlooked something? Thank you!
Upvotes: 4
Views: 4251
Reputation: 22490
It only validate at the time of targeted
element, not with other Element .Better use for Each function they validated all element change
document.querySelectorAll("input").forEach(function(a) {
a.addEventListener("change", function() {
console.log(this.checked);
console.log("checked radio value="+this.value);
if (!this.checked) console.log("do something");
})
})
<input type="radio" name="type" checked="checked" value="guest" />
<input type="radio" name="type" value="walk_in" />
Or if you need validate check and Uncheck*(like toggle)* use with type=checkbox
instead of radio
.
Radio
button not have toggle
checkbox have toggle
document.querySelector("input").addEventListener("change", function(ev) {
console.log(ev.target.checked);
if (!ev.target.checked) console.log("do something");
});
<input type="checkbox" name="type" checked="checked" value="guest" />
<input type="checkbox" name="type" value="walk_in" />
Upvotes: 2