Chinese input method does not trigger the onkeyup event solution

  • 2020-03-30 03:32:34
  • OfStack

These two days to do a real-time monitoring of text box input function, encountered the Chinese input method can not trigger the onkeyup event disgusting problem.

The specific manifestation is as follows:

When listening for an input keyup event, the English input method can detect the change of the value of the text box through the keyup event in real time, but when the input method becomes Chinese, the keyup event of the input will not be triggered normally. That's the way we wrote it first.


<html>
<head>
<script type="text/javascript" src="//www.jb51.net/static/js/jquery-1.4.2.min.js"></script>
</head>
<body>
  <p>
     use keyup Event detection text box content: 
  </p>
  <p>
    <input type="text" name="keyup_i" id="keyup_i" autocomplete="off"/>
    <span id="keyup_s"></span>
    <script type="text/javascript">
      $('#keyup_i').bind('keyup', function(){
        $('#keyup_s').text($(this).val());
      })
    </script>
  </p>
</body>
</html>

As you can see, this approach encounters a problem where the Chinese language cannot trigger the keyup event. Then seek solution, think of baidu's search bar prompt seems to be without this problem, then began to look at baidu js. Baidu's js is ugly... The method name is a single letter, and it turns out that timeout is used to make a timer to monitor the changes in the input box. Not very happy with this approach. So I continued to look for a better solution, so I found two events, oninput and onpropertychange.

Oninput is available under firefox, and onpropertychange is available under ie. There are some differences between the two methods.

Oninput can only detect the change of the property value, while onpropertychange can detect the change of all the properties containing value. So we started changing it to look like this.


<html>
<head>
<script type="text/javascript" src="//www.jb51.net/static/js/jquery-1.4.2.min.js"></script>
</head>
<body>
  <p>
     use oninput As well as onpropertychange Event detection text box content: 
  </p>
  <p>
    <input type="text" name="inputorp_i" id="inputorp_i" autocomplete="off"/>
    <span id="inputorp_s"></span>
    <script type="text/javascript">
      //First judge the browser is not evil IE, there is no way to write things also have IE users
      var bind_name = 'input';
      if (navigator.userAgent.indexOf("MSIE") != -1){
        bind_name = 'propertychange';
      }
      $('#inputorp_i').bind(bind_name, function(){
        $('#inputorp_s').text($(this).val());
      })
    </script>
  </p>
</body>
</html>

Related articles: