In this post we are going to see that how to formatting the
number entered in the server side text box.
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="Blogging.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript"> // This function is called when the focus moved from Text Box function formatNumber() { // Get the Controls value var strAmount = document.getElementById("<%=txtAmount.ClientID%>").value; // Replace the prefix and suffix spaces var dblAmount = strAmount.replace(/^s+|s+$/g, ''); //check the input is not a empty string if (dblAmount != '') { // check the input is a valid number if (isNaN(dblAmount)) { // Alert the User alert("Please enter only whole number"); // Clear the values document.getElementById("<%=txtAmount.ClientID%>").value = ""; } else { // Append zeros var strAmount = dblAmount + "." + "00"; //strAmount = strAmount.replace(/^s+|s+$/g, ''); document.getElementById("<%=txtAmount.ClientID%>").value = strAmount; } } } // Called when the focus set on the Text Box function removeZeros() { // Get the Controls value var strAmount = document.getElementById("<%=txtAmount.ClientID%>").value; // Replace the prefix and suffix spaces strAmount = strAmount.replace(/^s+|s+$/g, ''); // Replace the Zeros and Dot var dblAmount = strAmount.replace(".00", ""); //check the input is a valid number if (dblAmount != '') { // check the input is a valid number if (isNaN(dblAmount)) { alert("Please enter only whole number"); } else { // Assign the value to text box document.getElementById("<%=txtAmount.ClientID%>").value = dblAmount; } } } </script> </head> <body> <form id="form1" runat="server"> Enter A Whole Number : <asp:TextBox ID="txtAmount" runat="server" onblur="formatNumber();" onfocus="removeZeros();"> </asp:TextBox> </form> </body> </html>
Let’s have a look at that line:
<asp:TextBox ID="txtAmount" runat="server" onblur="formatNumber();" onfocus="removeZeros();"></asp:TextBox>
Which declares ASP.Net text box, with 2 client side events “onblur” and “onfocus”.
Onfocus – used to call a javascript function when the focus
set on that control. That is when you click on the text box this will fired.
Onblur – Used to call a javascript function when the focus
is moved to next control. When the user press tab key this event triggered.
In the javascript functions “formatNumber” and “removeZeros”
I have used some regular expression to remove the leading and trailing spaces.
To run this program, just copy and paste that code in a webform and hit F5.
Please go thru the comments in the javascript for better understanding.
Provide your valuable comments to improve my articles.
Hope this helps a bit!
0 comments :