Jan Anderssen
Jan Anderssen

Reputation: 95

How to make jQuery recognize radiobutton change

I have two radio buttons, first makes the text red, the other makes it yellow. but i cant make it blue. please help thanks.

Solution: http://jsfiddle.net/h6ye7/17/

<form>
    Option 1<input type="radio" name="opt" class="radio1" value="Option 1" />
    Option 2<input type="radio" name="opt" class="radio1" value="Option 2" />
</form>

<div class="text">sad dsffsadf sdsdf sfadfsd</div>


$(document).ready(function(){
    $('input[type=radio]').change(function(){
        if($('.radio1').is(':checked'))
        {
            $('.text').css('background-color', 'red');
        }
        else
        {
            $('.text').css('background-color', 'yellow');
        }
    });
});

Upvotes: 1

Views: 150

Answers (3)

ComFreek
ComFreek

Reputation: 29424

.radio1 selects both radio inputs!

There are several options:

  • Assign an ID

  • Use .eq():

    if ($(".radio1").eq(0).is(':checked'))
    

    → jsFiddle

  • Use :first

    if ($(".radio1:first").is(':checked'))
    

    → jsFiddle

  • If you really want to, you can also assign different classes (I do not recommend this method for the simple reason that IDs are meant to be used in this case instead of classes!)

    HTML:

    Option 1<input type="radio" name="opt" class="radio1" value="Option 1" />
    Option 2<input type="radio" name="opt" class="radio2" value="Option 2" />
    

    JS (the same as you had at the beginning):

    if ($(".radio1").is(':checked'))
    

    jsFiddle

Upvotes: 2

Jan Anderssen
Jan Anderssen

Reputation: 95

I gave a different class to second radio button .radio2 and that solved it.

http://jsfiddle.net/h6ye7/17/

<form>
    Option 1<input type="radio" name="opt" class="radio1" value="Option 1" />
    Option 2<input type="radio" name="opt" class="radio2" value="Option 2" />
</form>

Upvotes: 0

Greenhorn
Greenhorn

Reputation: 1700

You can use :first to do this:

$('input[type=radio]').change(function(){
    if($('.radio1:first').is(':checked'))
    {
        $('.text').css('background-color', 'red');
    }
    else
    {
        $('.text').css('background-color', 'yellow');
    }
});

Demo Fiddle

Upvotes: 0

Related Questions