1

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

2 Answers 2

2
(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

0
2

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.

1
  • I am fully aware of this, but I prefer to handle this with JavaScript. Thanks for the info sir, I appreciate it :)
    – Küroro
    Dec 12, 2017 at 10:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.