Jquery – Simple show hide div with radio button jQuery


I have this jQuery:

$(document).ready(function() {

        var divId = $(this).attr("id");

        if ($(this).is(":checked")) {
            $("." + divId).show();
        else {
            $("." + divId).hide();



divs should show/hide depending if inputs are checked/unchecked

EDIT: I should mention that using checkboxes the divs DO show and hide, but with radios they just show :(.

It works with checkboxes but not radio buttons, why is that?


Best Solution

It's because radio belongs to the same name name='same', so jQuery detects that it is selected.

When you fire change event on radio, jQuery finds out that 1 of radio is selected so it shows proper div. But next time, when you click another one, yet same radio input is still selected (belongs to same name group). Basically what I did, is to add class check to your divs to hide/show and when firing change on radio, I'm hiding them all and then showing only the proper one.

Here's updated code: