onchange not working with radio button

Florian picture Florian · Jan 25, 2011 · Viewed 41k times · Source

I have a few radio buttons which should call hider(something); when they change, meaning when they are checked or unchecked. This works, i.e. when checked they call the JS function, however, if they're unchecked due to selecting another radio button from that group, it does not call the js script again.

Do I need to use something else than onchange?

This is what the radio buttons look like at the moment:

<input name="ostype" type="radio" value="0" onchange="hider(solaris);">solaris
<input name="ostype" type="radio" value="1" onchange="hider(linux);">linux

My hider function is currently:

function hider(divid) {
 if ($(divid).is('.hidden')) {
  $(divid).removeClass('hidden');
 } else {
  $(divid).addClass('hidden');
 }
}

Answer

Robbert picture Robbert · Aug 3, 2013

Since this question is still not answered correctly yet ranks quite high for me in Google for "radio button onchange", here's a proper solution for anyone still looking.

If you're using jQuery, just use jQuery's attribute selector as noted by Flavius Stef.

OP, it's not entirely clear what your code does. Let's assume in your code you want to add the "hidden" class to whatever radio button is active.

$("your selector here").change(function() {
    $('input[name="' + this.name + '"]').removeClass("hidden");

    $(this).addClass("hidden");
});

Please note the difference between $(this) (the jQuery object) and this (the DOM object). Basically I'm removing the "hidden" class from every input that goes by the same name, and then I add the "hidden" class to the current input.

Of course I'm assuming here that you're not using duplicate names for different inputs on the page. Also note that this would only work for radio buttons, as the radio button "change" event only fires when activated, not when deactivated.

Listening for onchange on both checkboxes and radio buttons

In my case, I wanted to add a "checked" class to active radio buttons and checkboxes. Since the checkbox fires the "onchange" event both when checked and unchecked, I needed a bit of extra code.

$('input[type="radio"]').change(function() {
    $('input[name="' + this.name + '"]').removeClass("checked");
    $(this).addClass("checked");
});

$('input[type="checkbox"]').change(function() {
    $(this).toggleClass("checked", ($(this).is(":checked")));
});

The latter function uses toggleClass to set the "checked" class if .is(":checked") is true.

Alternatively you might want to combine the two functions into something like:

$('input[type="radio"], input[type="checkbox"]').change(function() {
    if(this.type == "radio")
        $('input[name="' + this.name + '"]').removeClass("checked");

    $(this).toggleClass("checked", ($(this).is(":checked")));
});

Either way, always be careful when listening for an onclick event as it will not fire when the input is activated through keyboard navigation.