javascript - js input box word limit problem
高洛峰
高洛峰 2017-07-05 10:38:10
0
6
948

js input box limits the number of words in the input box, the following code

<input type='text' onkeyup="checkNumber($(this))">

function checkNumber($this){
    let val=$this.val();
    if(val.length > 10 ){
        alert('字数超过10');
    }
}

During the actual process, the following problems were discovered, as shown in the figure:

In the input method, the letters are displayed first, and then the pinyin of the letters is converted into Chinese characters. Therefore, it may be that when inputting, the number of letters plus Chinese characters exceeds the limited number of characters. How to solve the problem?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(6)
小葫芦
<input type="text" maxlength="10">
迷茫

oninput="checkNumber($(this))"

代言

You don’t need alert, just add a red box after the input box

给我你的怀抱

We imagine that the input is also in full English or Chinese, and the length needs to be limited to less than 10, then maxlength="10" is required. The checkNumber function then determines whether the input contains Chinese characters, and if so, determines whether the last character is in English. . If there is no Chinese explanation and it is in pure English, it will prompt you. It is difficult to judge the shortcomings of the plan if both Chinese and English exist together.

ringa_lee

The following example, I wonder if it will help you

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>input 事件兼容处理以及中文输入法优化</title>
</head>
<body>
    <input type='text'>
    <script>
        var input = document.querySelector('input');
        var isLock = false;
        //当浏览器有非直接的文字输入时, compositionstart事件会以同步模式触发.
        input.addEventListener('compositionstart', function(){
            isLock = true;
        })
        //当浏览器是直接的文字输入时, compositionend会以同步模式触发.
        input.addEventListener('compositionend', function(){
            isLock = false;
        });
        input.addEventListener('input',function(e){
            if(!isLock)console.log(this.value);
        });
    </script>
</body>
</html>
曾经蜡笔没有小新

Replace the onkeyup event with the onblur event to solve the problem.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template