0

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/

Edward
  • 1,806
  • 5
  • 26
  • 36

2 Answers2

2

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/

kamil
  • 3,482
  • 1
  • 40
  • 64
0

This is because you cannot un-check a radio button like checkboxes.

To accomplish your task you must make a few changes to your code:

$(document).ready(function() {

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

        if ($(this).is(":checked")) {
            $("." + divId).show();
            $("." + divId).siblings('[class^=check]').hide();

        }
        else {
            $("." + divId).hide();
        }

    });

});

Fiddle

writeToBhuwan
  • 3,233
  • 11
  • 39
  • 67