Frage

I have the following Jquery validation limits text to 400 maxlength. It works great with plain text, but does not seem to work when pasting from word which contains formatting like line breaks, spacing, etc..? =

$('textarea[maxlength]').keyup(function(){
                //get the limit from maxlength attribute
                var limit = parseInt($(this).attr('maxlength'));
                //get the current text inside the textarea
                var text = $(this).val();
                //count the number of characters in the text
                var chars = text.length;

                //check if there are more characters then allowed
                if(chars > limit){
                    //and if there are use substr to get the text before the limit
                    var new_text = text.substr(0, limit);

                    //and change the current text with the new text
                    $(this).val(new_text);
                }
War es hilfreich?

Lösung

Try this...

function validateLength(textareaElement) {
    // your logic here, use textareaElement instead of $(this)
}
$('textarea[maxlength]').keyup(function(eventObject) {
    window.setTimeout(function() {
        validateLength($(eventObject.target));
    , 1);
});

The timeout of 1 millisecond should be enough to "escape the inner scope" of the keyup event and allow you to get the correct string value of your textareaElement.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top