Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery help to enforce maxlength on textarea?

Here is Jquery to enforce maxlength for textarea when you add the attribute "maxlength". Maxlength is not supported with IE. How do I adjust my code to handle multiple textarea(s) on the page? Currently if I add text to any textarea, they all countdown with the same value.

Jquery:

$(document).ready( function () {

maxLength = $("textarea").attr("maxlength");
    $("textarea").after("<div><span id='remainingLengthTempId'>" 
              + maxLength + "</span> remaining</div>");

    $("textarea").bind("keyup change", function(){checkMaxLength(this.id,  maxLength); } )

});

function checkMaxLength(textareaID, maxLength){

    currentLengthInTextarea = $("#"+textareaID).val().length;
    $(remainingLengthTempId).text(parseInt(maxLength) - parseInt(currentLengthInTextarea));

    if (currentLengthInTextarea > (maxLength)) { 

        // Trim the field current length over the maxlength.
        $("textarea").val($("textarea").val().slice(0, maxLength));
        $(remainingLengthTempId).text(0);

    }
}

Html:

Skills:
<textarea id="1" maxlength="200" rows="10" cols="60" ></textarea>

Postions:
<textarea id="2" maxlength="200" rows="10" cols="60" ></textarea>

Comments
<textarea id="3" maxlength="100" rows="10" cols="60" ></textarea>
like image 726
Chaka Avatar asked Feb 22 '13 19:02

Chaka


People also ask

How do I add Maxlength to textarea?

Then use JavaScript to limit user input: $(function() { $("textarea[maxlength]"). bind('input propertychange', function() { var maxLength = $(this). attr('maxlength'); if ($(this).

Does textarea have Maxlength?

You can set the size of a text area using the cols and rows attributes. To limit the number of characters entered in a textarea, use the maxlength attribute. The value if the attribute is in number.

Which attribute is used to limit the text to be given in the textarea Maxlength?

The maxlength attribute defines the maximum number of characters (as UTF-16 code units) the user can enter into an <input> or <textarea> . This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the input or textarea has no maximum length.


1 Answers

This is the best solution! Put this into your script tag in HTML code

$("textarea[maxlength]").on("propertychange input", function() {
    if (this.value.length > this.maxlength) {
        this.value = this.value.substring(0, this.maxlength);
    }  
});

and now use <textarea maxlength="{your limit}"></textarea> for {your limit} chars limit.

like image 120
X9DESIGN Avatar answered Oct 03 '22 06:10

X9DESIGN