Archive for the ‘JavaScript’ Category

Trimming text using JavaScript

January 14, 2010

The following code snippet can be used to trim the leading and trailing blanks in a textbox using JavaScript. Here the value of the HTML control is trimmed in the trimText function using reg expressing in JavaScript. If the trimText function is called in onblur event of a textbox, then text in the textbox will be trimmed.

function trimText(textBox)
{
    var textValue = textBox.value;
    textValue = textValue.replace(/(\s+$)|(^\s+)/g, '');
    textBox.value = textValue;
}

Call the above function in the following Server side and client side HTML controls

<asp:TextBox ID="txtLoginID" runat="server" Width="147px" onblur="trimText(this)" > </asp:TextBox>
<input id="txtUserName" type="text" maxlength="15" onBlur=" trimText(this)" />

In code behind, add the following statement in page load

txt1.Attributes.Add("onBlur", "trimText()");

I have posted this code snippet in dotnetspider.com. Click here to view it.