Monday, February 25, 2013

Limit Number Of Characters In a ASP.NET Multiline TextBox using jQuery


.aspx Markup:

<div class="smallDiv">
<h2>Type into this textbox which accepts 50 characters overall</h2>
<asp:TextBox ID="tb1" runat="server" TextMode="MultiLine"/>
(This textbox accepts only 50 characters)
<span id="spn"></span>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"/>
<span id="error"></span>
<br />
Tip: Clicking on the Submit button when number of characters are
less than 50, results in a postback to same page. If you exceed 50
characters, the exceeded characters are printed below the textbox
and a postback is prevented.
</div>

Jquery Script:
<script type="text/javascript">
$(function() {
var limit = 50;
var $tb = $('textarea[id$=tb1]');
$tb.keyup(function() {
var len = $(this).val().length;
if (len > limit) {
$(this).addClass('exceeded');
$('#spn').text(len - limit + " characters exceeded");
}
else {
$(this).removeClass('exceeded');
$('#spn').text(limit - len + " characters left");
}
});
$('input[id$=btnSubmit]').click(function(e) {
var len = $tb.val().length;
if (len > limit) {
e.preventDefault();
}
});
});
</script>

.CSS
.exceeded
{
background-color:red;
}




No comments:
Write comments
Recommended Posts × +