I have a textbox with a Css class called 'required'. When a user click a button, I'd like to add additional Css Class to the textbox called 'error' without removing the 'required' class. I want to accomplish this from code-behind.
addClass() - Adds one or more classes to the selected elements. removeClass() - Removes one or more classes from the selected elements. toggleClass() - Toggles between adding/removing classes from the selected elements. css() - Sets or returns the style attribute.
In this article, we will see how to dynamically create a CSS class and apply to the element dynamically using JavaScript. To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript.
Yes you can - first capture the event using onmouseover , then set the class name using Element. className . If you like to add or remove classes - use the more convenient Element. classList method.
Dynamically change DIV CSS class from code behind in ASP.Net using C# and VB.Net. There is a label in the listview : <asp:Label ID="lblPernah" runat="server" Text='<%# Eval("pernah") %>' Visible="false" />, whose contents are 0 or 1.
I decided to create extension methods for WebControl to have a generic solution. Here's my code:
public static class WebControlExtensions
{
public static void AddCssClass(this WebControl control, string cssClass)
{
if (string.IsNullOrEmpty(control.CssClass))
{
control.CssClass = cssClass;
}
else
{
string[] cssClasses = control.CssClass.Split(' ');
bool classExists = cssClasses.Any(@class => @class == cssClass);
if (!classExists)
{
control.CssClass += " " + cssClass;
}
}
}
public static void RemoveCssClass(this WebControl control, string cssClass)
{
if (!string.IsNullOrEmpty(control.CssClass))
{
string[] cssClasses = control.CssClass.Split(' ');
control.CssClass = string.Join(" ", cssClasses.Where(@class => @class != cssClass).ToArray());
}
}
}
You can set the CssClass property of the ASP.NET Textbox control. To add more than one CSS class for an element, just separate it with a space:
MyTextBox.CssClass = "class1 class2";
You can put this in your OnClick event handler:
<asp:TextBox ID="MyTextBox" runat="server" OnClick="MyTextBox_Click" />
Then in code-behind:
void MyTextBox_Click(Object sender, EventArgs e) {
MyTextBox.CssClass = "class1 class2";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With