Jquery – Simple show hide div with radio button jQuery

jqueryshow-hide

I have this jQuery:

$(document).ready(function() {

    $("input[type=radio]").change(function()
    {
        var divId = $(this).attr("id");

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

    });
    $("input[type=radio]").change();

});

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?

http://jsfiddle.net/qarZb/1/

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:

http://jsfiddle.net/qarZb/6/