How to change the class attribute of an element using javascript.
Introduction
This article is a very basic level article. As developers move from one project to another project, it is always nice to have some handy functionalities in a single location.
In short, I want the ability to change the class attribute of an html element using the javascript. When the user enter a non numeric value in the text box and moves aways from the control, the script checks to see if the entered value is a numeric or not. If the value is not a numeric it highlights the textbox with a red color.
This article is organized into 3 sections.
1. Stylesheet
2. Script to change the class attribute
3. HTML element (in this case asp.net textbox).
Using the code
StyleSheet:
In the head section of html file add the following stylesheet. There are 2 class names defined in the stylesheet.
The class name ".TextBox" is used to represent a valid state and the class name ".ErrorTextBox" is used to represent the invalid state. Both of the stylesheet elements share the same attributes with an exception of ".ErrorTextBox" has a different border color.
<style type="text/css">
.ErrorTextBox,
.TextBox {
font-size:1em;
font-family:tahoma,arial,sans-serif;
border-style:solid;
border-width:1px;
border-color:#7F9DB9;
}
.ErrorTextBox
{
border-color:red;
}
</style>
Script to change the class attribute.
Add the following javascript in the head section.
This javascript function reads the value of the textbox and checks if the value is a numeric or not. If the value is a numeric it sets the class attribute of the textbox to ".TextBox" otherwise it sets the class attribute to ".ErrorTextBox". In order to achieve the ability the "setAttribute" method is used. It takes the 2 parameters a) The name of the attribute to modify b) The value to set for the attribute.
<script type="text/javascript">
function ValidateData() {
var cntltxtInput = document.getElementById("<%=txtInput.ClientID%>");
if (cntltxtInput)
{
if(isNaN(cntltxtInput.value))
cntltxtInput.setAttribute("class", "ErrorTextBox");
else
cntltxtInput.setAttribute("class", "TextBox");
}
}
</script>
Asp.net textbox element.Points of Interest
Add an asp.net textbox inside the body of the html file. The javascript function is attached to the onblur event of the textbox control. When the user enter a value in the text box and moves aways the focus from the text box, onblur event is fired.
<!--Step 3 -->
<asp:TextBox ID="txtInput" onblur="return ValidateData();" runat="server"></asp:TextBox>
Hope this helps. Happy programming.
发表评论
27vMI5 Thanks so much for the post.Thanks Again. Fantastic.