Jquery help to enforce maxlength on textarea?

前端 未结 4 1904
南方客
南方客 2020-12-31 14:12

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 tex

4条回答
  •  盖世英雄少女心
    2020-12-31 15:11

    The solution is here:

    http://web.enavu.com/daily-tip/maxlength-for-textarea-with-jquery/

    $(document).ready(function() {
    
        $('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);
            }
        });
    
    });
    

提交回复
热议问题