Thursday, September 26, 2013

Restrict max length textarea using jQuery and Javascript

 Draw Textarea control with class name comment
<asp:TextBox ID="txtComment" runat="server" Text="" TextMode="MultiLine" CssClass="comment" MaxLength="1000" />

Container to display number of chars are remaining
<div class="form_content" id="DivQueryLength"> 1000 characters left</div>

jQuery method to validate and show the messages

$(document).ready(function() {
        $(".comment").keyup(function() {
            validateLimit(this, 'DivQueryLength', 1000);
        });
        $(".comment").keydown(function() {
            validateLimit(this, 'DivQueryLength', 1000);
            //return checkMaxLen(event, this, 1000);
        });
 });

function validateLimit(obj, divID, maxchar) {
    objDiv = get_object(divID);
    if (this.id) obj = this;
    var remaningChar = maxchar - obj.value.length;
    if (objDiv) {
        objDiv.innerHTML = remaningChar + " characters left";
    }
    if (remaningChar <= 0) {
        obj.value = obj.value.substring(maxchar, 0);
        if (objDiv) {
            objDiv.innerHTML = "0 characters left";
        }
        return false;
    }
    else
    { return true; }
}

function get_object(id) {
    var object = null;
    if (document.layers) {
        object = document.layers[id];
    } else if (document.all) {
        object = document.all[id];
    } else if (document.getElementById) {
        object = document.getElementById(id);
    }
    return object;
}

No comments:

Post a Comment