16

I have the following ASP.Net check box control added to a page:

<asp:CheckBox ID="chkActive" runat="server" CssClass="myClass" />

But when the page gets rendered it ignores the value of the CssClass property:

<input name="ctl00$mainContent$chkActive" id="ctl00_mainContent_chkActive" type="checkbox" value="on"/>

Any ideas how to apply the css class to the ASP.Net check box?

Thanks Alan.

5 Answers5

25

I found a different answer to this, you can use the property

MyCheckBox.InputAttributes["class"] = "myClass";

to assign a class directly to an asp checkbox from the codebehind. Just noting this since I found this post through Google and the answer specified wouldn't work for me.

FTWinston
  • 1,019
  • 10
  • 16
Will P.
  • 8,437
  • 3
  • 36
  • 45
9

This post is quite old, but I'll post my solution to help anyone coming from google (like me).

You can use the child selector > in jQuery, because the wrapping span has the CssClass that you specified, and one input child. In your code:

$('.myClass > input').addClass("myClass");
j0k
  • 22,600
  • 28
  • 79
  • 90
Taro dude
  • 99
  • 1
  • 2
  • charm for me too. I even added a different class than the one starting with: $('.form-control > input').addClass("biggercheckbox"); I put this in the $(document).ready(function () – JustJohn Aug 19 '16 at 06:41
9

Ok, when you apply a CssClass to the ASP.Net check box control it applies the class to a span that wraps the check box. Because the css class isn't applied directly to the element it doesn't override the class that has been applied to all input elements.Therefore I used jQuery to select the element and apply the necessary style.

$("input[type=checkbox]").addClass("myClass");
  • Yes that is just what I needed as I had to update a asp.net webforms application and noticed the cssclass was adding to the outer span and then my jquery code for checkbox logic would not work. This fix is nice, I actually do this instead though $("[id$=Out]").addClass("out"); – Tom Stickel Sep 14 '15 at 21:18
-1

You could wrap it in a span with a class.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • If you add a `` before the `CheckBox`, don't forget to update your CSS. – Neil Knight Jul 11 '11 at 15:52
  • The rendered code does this and that is the problem, especially when you migrate to newer boostrap versions, the input will not inherit from the span that asp generates as an input wrapper. – KeyOfJ Dec 15 '21 at 19:15
-2

You can alos just set the css class like

    <asp:CheckBox ID="cbValittu" runat="server" Checked='<%# Eval("Valittu")%>' Class="checBoks" />

Css class can look something like:
.checBoks input
{
    width: 18px;
    height: 18px;
    vertical-align:middle;
}
Nooby
  • 1