js实现文本框输入文字个数限制代码

时间:2021-11-03 20:21:18

html:

<div class="curr_eval_box">
                <input type="hidden" name="cource_id" value="{$_GET['cource_id']}">
                <input type="hidden" name="order_id" value="{$_GET['order_id']}">
                <div class="curr_area">
                    <label for="">课程评价</label>
                    <textarea name="comment_content" id="comment_content" cols="30" rows="10" placeholder="快分享你的购买心得吧~"></textarea>
                    <span id="write_num">0/5</span>
 </div>

js:

var contentBox = document.getElementById('comment_content');
        var max = +document.getElementById('write_num').innerHTML.split('/')[1];
        function maxStr (dom, num) {
            var flag = true;
            dom.onkeydown = function (e) {
                if (!flag) {
                    return false;
                }
                flag = false;
                 var that = this;
                let nowLength = this.value.split('').length;
                if (nowLength === max&& e.keyCode !== 8) {
                    return false;
                }

                 setTimeout(function () {
                    document.getElementById('write_num').innerHTML = that.value.split('').length + '/' + max;
                },0);

                
            }
            dom.onkeyup = function () {
                flag = true;
            }
        }
        maxStr(contentBox, max);