Trimming text using JavaScript

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: