search

Home  >  Q&A  >  body text

javascript - js input box word limit problem

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?

高洛峰高洛峰2727 days ago950

reply all(6)I'll reply

  • 高洛峰

    高洛峰2017-07-05 10:40:10

    <input type="text" maxlength="10">

    reply
    0
  • 迷茫

    迷茫2017-07-05 10:40:10

    oninput="checkNumber($(this))"

    reply
    0
  • 代言

    代言2017-07-05 10:40:10

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

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-07-05 10:40:10

    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.

    reply
    0
  • ringa_lee

    ringa_lee2017-07-05 10:40:10

    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>

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 10:40:10

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

    reply
    0
  • Cancelreply