HOW TO RESET THE BACKGROUND OF PARENT OF THE RADIO BUTTON WHEN UNCHECKED?

jacob rasel

Total Post:88

Points:616
Posted by  jacob rasel
 1533  View(s)
Ratings:
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?

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: How to reset the background of parent of the radio button when unchecked?

    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>

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!