Controls inside an ASP.NET UpdatePanel cannot be bound to jQuery events after a partial postback. Here are some tips using pageLoad():
jQuery
ASP.NET MultiLine TextBox MaxLength Validation
There have been many articles and forums addressing the fact that the MaxLength property of the ASP.NET TextBox does not work when you set TextMode to MultiLine. The majority of these solutions use the KeyPress and OnBlur events. This brings with it lots of JavaScript and a host of browser issues. I was impressed by the RegularExpressionValidator options because they can tie in to the AJAX ValidatorCalloutExtender. I also like the server-side validation that you get with the native validation controls.
- A plethora of options at the ASP.NET forums
- Using JavaScript KeyPress and MS AJAX
- Using ASP.NET RegularExpressionValidator
- Using JQuery at StackOverflow
The solution I settled on is a combination of all the above. I use an ASP.NET RegularExpressionValidator on the MultiLine TextBox. The code looks like this:
<asp:TextBox runat="server" ID="txtDescription" TextMode="MultiLine" Rows="5" Width="300" />
<asp:RegularExpressionValidator runat="server" ID="revtxtDescription" ControlToValidate="txtDescription" ErrorMessage="Exceeds 500 character maximum." ValidationExpression="^[\s\S]{0,500}$" Display="None" />
<ajax:ValidatorCalloutExtender ID="vcerevtxtDescription" runat="server" TargetControlID="revtxtDescription" />
Good so far, but to quote Mark Hildreth:
“I agree that that works for preventing users from posting too much text, however it does’t prevent them from typing more than 500 characters into the box. The validators only perform their validation in the onchange event which is not triggered on every key stroke. Imagine your dismay if you spent 10 minutes typing into a textbox, only to have the form say you have exceeded the 500 character limit?”
The JavaScript below will call this RegularExpressionValidator every second. I find that it does not noticeably slow down the form.
<script type="text/javascript">
$(document).ready(function () {
setInterval("validateDescription();", 1000);
});
function validateDescription() {
var myValidator = document.getElementById("<%= revtxtDescription.ClientID %>");
ValidatorValidate(myValidator);
}
</script>
Now as the user is typing, they will be warned within one second of exceeding 500 characters. If they paste into the textbox, it will alert them too.
jQuery Get Next Textbox in a GridViewRow
In a GridView I have a column of checkboxes and a column of textboxes. I wanted to modify the value of the textbox when the checkbox is checked. jQuery is the perfect fit for this. Here is the code I used:
$(function () {
var $inp = $('input:checkbox');
$inp.bind('click', function () {
var textbox = $(":input:text:eq(" + $inp.index(this) + ")");
if (this.checked == true) {
textbox.val('123ABC');
textbox.attr('disabled', 'disabled');
} else {
textbox.attr('disabled', '');
}
});
});
This post uses ideas from Suprotim Agarwal.