Home > DeveloperSection > Forums > How to reset the background of parent of the radio button when unchecked?
jacob rasel
jacob rasel

Total Post:88

Points:616
Posted on    September-25-2013 9:05 AM

 CSS-CSS3 CSS-CSS3 
Ratings:


 1 Reply(s)
 1132  View(s)
Rate this:

I have created one group of radio buttons in a table like

    <table cellpadding="0" cellspacing="0" border="0">

    <tbody>

        <tr>

            <td>

                <input type="radio" name="radios" id="8-9" />

                <label for="8-9">08-09 am</label>

            </td>

        </tr>

        <tr>        

            <td>

                <input type="radio" name="radios" id="9-10" />

                <label for="9-10">09-10 am</label>

            </td>

        </tr>

    </tbody>

</table>

and when any of the radio button clicked then the background of parent is need to be changed and JQuery for it is like-

$(document).on('click', '#8-9', function (event) {

    $checked = $("#8-9").is(':checked');

    if ($checked) {

        $(this).parent().css("background-color", "#000");

        $(this).parent().css("color", "#fff");

    } else {

        $(this).parent().css("background-color", "#ff0000");

        $(this).parent().css("color", "#fff");

    }

});

$(document).on('click', '#9-10', function (event) {

    $checked = $("#9-10").is(':checked');

    if ($checked) {

        $(this).parent().css("background-color", "#000");

        $(this).parent().css("color", "#fff");

    } else {

        $(this).parent().css("background-color", "#252525");

        $(this).parent().css("color", "#fff");

    }

});

this code is working , when radio is clicked the background of parent is changed, but when radio is unchecked the background of parent is not been reset to default. Is there any mistake in my script or any other way is there of this?



Pravesh Singh

Total Post:411

Points:2881
Posted on    September-25-2013 10:04 AM

Hi Jacob,

You can optimize the code like below

$(document).on('change', '.radioBtn', function (event) {

    $('.radioBtn').parent().css("background-color", "#FFF").css("color", "#000");

    $(this).parent().css("background-color", "#000").css("color", "#fff");

});

And modify the HTMl like this,

<table cellpadding="0" cellspacing="0" border="0">

    <tbody>

        <tr>

            <td>

                <input type="radio" name="radios" id="8-9" class="radioBtn" />

                <label for="8-9">08-09 am</label>

            </td>

        </tr>

        <tr>

            <td>

                <input type="radio" name="radios" id="9-10" class="radioBtn"/>

                <label for="9-10">09-10 am</label>

            </td>

        </tr>

    </tbody>

</table>


Don't want to miss updates? Please click the below button!

Follow MindStick