Solution to textarea word limit

Option One

  • Input is a standard browser event, which is generally applied to the input element. When the value of the input changes, it will occur. Whether it is keyboard input or mouse paste changes, the changes can be monitored in time, propertychange, as long as the current object property changes.
<textarea id="area" name="ss" placeholder="请输入文本内容"></textarea>  
<p><span id="text-count">20</span>/20</p>  

<script type="text/javascript">  
    /*字数限制*/  
    $("#area").on("input propertychange", function() {  
        var $this = $(this),  
            _val = $this.val(),  
            count = "";  
        if (_val.length > 20) {  
            $this.val(_val.substring(0, 20));  
        }  
        count = 20 - $this.val().length;  
        $("#text-count").text(count);  
    });  
</script>  

Option II

  • Bind the change and keydown events at the same time, and then cooperate with the maxlength property
<textarea  
    maxlength="100" 
    onchange="this.value=this.value.substring(0, 100)"
    onkeydown="this.value=this.value.substring(0, 100)" 
    placeholder="添加备注信息,不超过100字" id="sk_notes"></textarea>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325568740&siteId=291194637