Suyash Gupta
Suyash Gupta

Reputation: 576

asp:checkbox color change when checked or unchecked

I have a checkbox inside a GridView and I want to change its color to red when unchecked and to green when checked.

How can I do this ?

<ItemTemplate>
   <asp:CheckBox ID="checkboxAttendanceStatus" BackColor="Red" runat="server" AutoPostBack="true" />
</ItemTemplate>

Upvotes: 1

Views: 9493

Answers (2)

Sunil
Sunil

Reputation: 21406

You can set the OnCheckChanged server-side event for the check box as in markup below. Then, all you need is to write code in server-side event to change the BackColor.

Markup

<ItemTemplate>
   <asp:CheckBox ID="checkboxAttendanceStatus" BackColor="Red" runat="server"
        AutoPostBack="true" OnCheckedChanged="checkboxAttendanceStatus_CheckedChanged"/>
</ItemTemplate>

C# code for server-side event

protected void checkboxAttendanceStatus_CheckedChanged(object sender, EventArgs e)
{
    CheckBox chk = sender as CheckBox;
    if (chk.Checked)
    {
        chk.BackColor = System.Drawing.Color.Green;
    } else
    {
        chk.BackColor = System.Drawing.Color.Red;
    }
}

Another approach using client-side code without any C#

If you wanted to implement this requirement completely on the client-side, then you could add the following JavaScript to your aspx page.

You do not need to subscribe to CheckChanged event of checkbox nor write any C# code. This approach needs only JavaScript/jQuery code.

<script type="text/javascript">
function pageLoad() {

    var checkboxes = $("[id*='checkboxAttendanceStatus']");

    checkboxes.each(function (i) {
        if (this.checked) {
            $(this).parent().css("background-color", "green");
        } else {
            $(this).parent().css("background-color", "red");
        }
    });
}
</script>

Upvotes: 1

VDWWD
VDWWD

Reputation: 35514

The easiest way is to use CSS with an adjacent sibling selector for the label since the generated html will look like this:

<input id="id" type="checkbox" name="id" /><label for="id">Label</label>

So set the color of the label based on the checked status of the CheckBox.

<style>
    input[type="checkbox"]:checked + label {
        color: blue;
        background-color: yellow;
    }

    input[type="checkbox"] + label {
        color: red;
        background-color: green;
    }
</style>

If you want to style the actual checkbox itself, you're gonna need a jQuery plugin or more complex CSS tricks. See this answer here

Upvotes: 0

Related Questions