VBeregovoy
VBeregovoy

Reputation: 29

jQuery hide/show div, with radio button control

I have few radio buttons with same name.

Office <input type="radio" name="owner_type" value="0" />
Agent <input type="radio" name="owner_type" value="1" />

and have part of jQuery code, which must show or hide part of code.

$('[name="owner_type"]').change(function(){
    if ($('[name="owner_type"]').val() == 1) {
        alert("it's 1 now");
        $('#agents').show();
    } else {
        alert("it's 0 now");
        $('#agents').hide();
    }
});

Alerts was added for debugging. It's always alert about 0. No matter which radio is checked now. I am hope, you can help me. Thank you

Upvotes: 0

Views: 1086

Answers (4)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67187

Try this, use a :checked selector

DEMO

$('[name="owner_type"]').change(function(){
    if($('[name="owner_type"]:checked').val() == 1) {
        alert("it's 1 now");
    $('#agents').show();
    } else {
        alert("it's 0 now");
    $('#agents').hide();
    }
});

Upvotes: 0

rajesh kakawat
rajesh kakawat

Reputation: 10896

try something like this

            $('input[name="owner_type"]').change(function(){
                if (this.value == 1) {
                    alert("it's 1 now");
                    $('#agents').show();
                } else {
                    alert("it's 0 now");
                    $('#agents').hide();
                }
            });

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

var $oTypes = $('input[name="owner_type"]').change(function () {
    //$('#agents').toggle($oTypes.filter(':checked').val() == 1);
    $('#agents').toggle(this.value == 1);
});
  1. Use the element selector before attribute selector
  2. Use toggle to set the display state

Upvotes: 0

palaѕн
palaѕн

Reputation: 73896

You can do this:

$('[name="owner_type"]').change(function () {
    if ($('[name="owner_type"]:checked').val() === "1") {
        alert("it's 1 now");
        $('#agents').show();
    } else {
        alert("it's 0 now");
        $('#agents').hide();
    }
});

Actually, you are doing this:

$('[name="owner_type"]').val()

which will always fetch you the value of the first radio button, whether it's checked or not.

In order, to get the value of the checked radio button on change event you can use the :checked selector as above.

Upvotes: 2

Related Questions