Introduction
This article is a very basic level article. As developers move from one project to another, 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 JavaScript. When the user enters a non numeric value in the text box and moves away 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:
- Stylesheet
- Script to change the class attribute
- 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
" which 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:
- The name of the attribute to modify
- 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
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 away the focus from the text box, onblur
event is fired.
<asp:TextBox ID="txtInput" onblur="return ValidateData();" runat="server"></asp:TextBox>
Hope this helps. Happy programming!
History
- 2nd June, 2011: Initial post
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.