Character Limiting in TextBox in ASP.NET using jQuery and display red when reaches out of limit
Introduction
Look at the images given blow that you frequently see on
websites. In this post you are going to learn this.
Screen when character reaches out of limit:-
Follow the steps to create such system.
Step 1
Add the reference of the jQuery file in head section of web
page, for example:
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
Step 2
Add the following jQuery method in head section of web page:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var txt = $("textarea[id$=txtComments]");
var txtMsg = $("label[id$=txtStatus]");
$(txt).keyup(function () {
var length = $(txt).val().length;
$(txtMsg).text("Total " + length + "
Characters out of 200.");
$(txtMsg).css("background-color", length >= 201 ? "#FF0000" : "#FFFFFF");
});
});
</script>
Step 3
Design the web page which contains TextBox, Label and a Button,
for example:
<div>
Enter your comment
<br />
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Height="164px" Width="298px"/>
<br />
<label id="txtStatus"></label>
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" />
</div>
Now look at my complete coding.
Complete Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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>ASP.NET
& jQuery Post</title>
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var txt = $("textarea[id$=txtComments]");
var txtMsg = $("label[id$=txtStatus]");
$(txt).keyup(function () {
var length = $(txt).val().length;
$(txtMsg).text("Total " + length + "
Characters out of 200.");
$(txtMsg).css("background-color", length >= 201 ? "#FF0000" : "#FFFFFF");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter your comment
<br />
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Height="164px" Width="298px"/>
<br />
<label id="txtStatus"></label>
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" />
</div>
</form>
</body>
</html>
I recommend you to download the attached file and check it. I
hope you like it. Thanks.
Comments
Post a Comment