Friday, May 22, 2009

Limit the characters in a multi row textbox

The maxlength property to limit the number of characters does not work on a multi row text box. We have to rely on custom JavaScript to limit the MaxLength functionality. Here is a snippet that does that.


function ValidateCharCount(txtBox, maxLength,controlName) {
var input;
var length;

input = txtBox.value;
length = input.length;

var allowedLength = new Number(maxLength);
if (length > allowedLength) {
txtBox.value = txtBox.value.substring(0, allowedLength);
alert(" Only " + maxLength + " characters are allowed in the field " + controlName);
txtBox.focus();
}
}


The function above takes three parameters. The first parameter is reference to the textbox control,second parameter is the max length of characters, third one is the textbox field description.
The function kicks in once the texbox loses focus, alerts the user if the character count exceeded the allowed length and then truncates the characters to the allowed length.

Usage:

<input type="text" rows="5" id="Description" onfocusout="ValidateCharCount(this,100,'Description')" />
<br/><br/>

Digg It! Add to del.icio.us Stumble This

1 Comment:

grimmier said...

Short sweet and to the point, perfect.