Unlike Textboxes, the <textarea> control doesn’t
support the Max Length property; hence there is no direct way to impose
maxlength for a textarea. However we can achieve this using jQuery.
Using jQuery we
can impose Max Length property to a textarea, by tracking the keypress and blur
events of the textarea, the keypress event makes sure that the user does not
type more than the allowed number of characters in the textarea, the blur event
takes care of values which are copied into the textarea, on blur, we will
truncate the text such that it doesn’t exceed the max allowed length.
Here is a full
example
<html xmlns="http://www.w3.org/1999/xhtml" >
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>TextBox</title>
<link type="text/css" href="Stylesheet.css" rel="Stylesheet" />
<script type="text/javascript" src="JavaScript/jquery-1.7.2.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#txtComment').keypress(function(evt) {
$('#txtComment').keypress(function(evt) {
var
maxLength = 50;
//
Allow Delete & BackSpace keys
if
(evt.keyCode == 8 || evt.keyCode == 46) return true;
//
Allow Shift, Ctrl & Tab Key
if
(evt.keyCode == 16 || evt.keyCode == 17 || evt.keyCode == 9) return true;
//
Allow Arrow Keys
if
(evt.keyCode == 37 || evt.keyCode == 38 || evt.keyCode == 39 || evt.keyCode ==
40) return true;
//
Check and restrict other Keys
if
($(this).val().length > maxLength) {
return
false;
}
});
//
$('#txtComment').blur(function() {
var
maxLength = 50;
var
text = $(this).val();
if
($(this).val().length > maxLength) {
$(this).val(text.substr(0,
maxLength));
}
});
});
</script>
</head>
<body>
<form id="frmTextBox" runat="server">
<div id="pageControls">
<asp:TextBox
ID="txtComment"
runat="server"
TextMode="MultiLine"></asp:TextBox>
</div>
<asp:TextBox
ID="txtComment"
runat="server"
TextMode="MultiLine"></asp:TextBox>
</div>
</form>
</body>
</html>
The above script will validate the txtComment textarea,
if you want the validation to be applied to all the textareas in
the page then replace txtComment
with
the word textarea
as follows
$('textarea').keypress(function(evt) {
$('textarea').blur(function() {
Related Posts
Asp.Net jQuery get Textbox Values
Asp.Net jQuery set Textbox Values
Asp.Net jQuery get Textbox Attributes
Asp.Net jQuery set Textbox Attributes
Asp.Net jQuery Apply style to all TextBoxes in the Page
Asp.Net jQuery Apply cssClass to all TextBoxes in the Page
Asp.Net jQuery change textbox style on focus
Asp.Net jQuery loop through Textboxes
Asp.Net jQuery Textbox set ReadOnly
Asp.Net jQuery Textbox Remove ReadOnly
Asp.Net jQuery Textbox Disable
Asp.Net jQuery Textbox Enable
$('textarea').keypress(function(evt) {
$('textarea').blur(function() {
Related Posts
Asp.Net jQuery get Textbox Values
Asp.Net jQuery Textbox set ReadOnly
Asp.Net jQuery Textbox Remove ReadOnly
Asp.Net jQuery Textbox Disable
Asp.Net jQuery Textbox Enable
No comments:
Post a Comment