views:

38

answers:

3

I need to change the bg color of a div containing a radio button when the user slects the button. I am using jquery - so its seems like there should be some simple way to accomplish this. I have my html setup something like this:

<div class="sales_box">
<table>
<tr>
<td class="radio_cell"><input type="radio"></td>
</tr>
</table>
</div>

<div class="sales_box">
<table>
<tr>
<td class="radio_cell"><input type="radio"></td>
</tr>
</table>
</div>
+3  A: 

Just handle the change event of the radio button and then use the closest() method of jQuery:

$(document).ready(function(){
    $('input:radio').change(function(){
       $(this).closest('div').css('background-color', 'red');
    });
});

And as redsquare has said, you shouldn't really set inline css. You should use the toggleclass function. I just used the css function as an example.

GenericTypeTea
this will change the td background
redsquare
@redsquare - No need for the downvote, give me change to correct it first.
GenericTypeTea
I did not -1 it
redsquare
Yeah, I'd like to change the div background color. Is there a way to use this method and target the div?
Thomas
use $(this).closest('div')
redsquare
also I would use toggleClass rather than set inline css
redsquare
That did it - thanks!
Thomas
@redsquare - sorry, just assumed as the downvote happened at the same minute you posted that it was you. Anyway, all corrected and working now.
GenericTypeTea
+1 for the corrections
redsquare
@GenericTypeTea OT - your blog throws a .net error!
redsquare
@redsquare - Forgot I had the link on SO. Removed it.
GenericTypeTea
A: 

Try

 $(function() {
        $(".radio_cell input[type=radio]").bind("click", function() {
            $(this).parents('div:first').css("background-color", "Blue");
        });
    });
josephj1989
closest is better here, this way gets all parents then filters
redsquare
A: 

I would use the toggleClass rather than setting inline css.

$(document).ready(function(){
    $('input:radio').change(function(){
       $(this).closest('div').toggleClass('highlight');
    });
});
redsquare
I just added a follow up to this regarding the deselect behavior:http://stackoverflow.com/questions/3078781/change-bg-on-radio-deselect
Thomas