Reputation: 668
I'm trying to create a custom styled radio button and handle its event with JavaScript. So the simple task is; add or remove a class when the radio was selected or deselected.
It can be achieved via the change
event but my problem was the deselection of the radio on a group is not firing the event.
How can I handle this?
P.S
Without using a framework will be better.
Here's my example code (fiddle):
(function() {
var input = document.querySelectorAll('input');
var callback = function(e) {
e.addEventListener('change', function() {
if (this.checked) {
this.classList.add('colored');
} else {
// I would like this one to be triggered when
// the radio button was deselected by the user.
this.classList.remove('colored');
}
});
}
Array.prototype.forEach.call(input, callback);
})();
Upvotes: 1
Views: 332
Reputation: 161
(function() {
var input = document.querySelectorAll('input');
var callback = function(e) {
e.addEventListener("change", function() {
var radios = document.getElementsByName('radio-group');
for( i = 0; i < radios.length; i++ ) {
if(radios[i].checked ) {
radios[i].classList.add('colored');;
}
else{
radios[i].classList.remove('colored');;
}
}
});
}
Array.prototype.forEach.call(input, callback);
})();
you have to go through each radio-button
Upvotes: 2
Reputation: 87203
No need of JavaScript for this. Use CSS :checked
& +
selector.
[type="radio"]:checked + label {
color: blue;
}
<input type="radio" class="colored" id="option-1" name="radio-group" checked>
<label for="option-1">Option 1</label>
<br>
<input type="radio" id="option-2" name="radio-group">
<label for="option-2">Option 2</label>
With JavaScript, you have to iterate over radio buttons and remove the class from unchecked radio buttons.
Upvotes: 2