Keypress event for Japanese text

后端 未结 2 806
余生分开走
余生分开走 2021-01-19 06:07
$(document).ready(function () {
    $(\"#id\").keydown(function () {

    });
})

This code perfectly works for everything(number,alphabet,symbol et

相关标签:
2条回答
  • 2021-01-19 06:16

    I had the same issue and I solved it using the input event.

    //calculate the length of a character
    function getLen(str){
        var result = 0;
        for(var i=0;i<str.length;i++){
          var chr = str.charCodeAt(i);
          if((chr >= 0x00 && chr < 0x81) ||
             (chr === 0xf8f0) ||
             (chr >= 0xff61 && chr < 0xffa0) ||
             (chr >= 0xf8f1 && chr < 0xf8f4)){
            //half width counted as 1
            result += 1;
          }else{
            //full width counted as 2
            result += 2;
          }
        }
        return result;
    };
    
    // trim the string by processing character by character
    function getTrimmedString(theString, maxLength){
    var tempLength = 0;
    var trimmedString = "";
    for (var i = 0; i < theString.length; i++) {
        tempLength = getLen(theString.charAt(i)) + tempLength;
        if(tempLength > maxLength){
            break;
        }else{
            trimmedString = trimmedString + theString.charAt(i);
        }
    }
    return trimmedString;
    }
    
    // limit the size of a field
    function limitCity(){
    var maxChars = 30;
    var cityVal = $("#city").val();
    var cityLength = getLen(cityVal);
    if (cityLength >= maxChars) {
        var trimmedString = getTrimmedString(cityVal, maxChars);
        $("#city").val(trimmedString);
    }
    }
    
    //bind the input event 
    $("#city").bind("input", limitCity);
    
    0 讨论(0)
  • 2021-01-19 06:26

    There's hardly anything you can do. "Japanese text" means an IME, which is a piece of software intercepting the keyboard input and helping you turn it into Japanese text. How this software interacts or doesn't interact with the browser and the browser's Javascript engine depends on the OS, IME, browser and the browser's Javascript engine. On some platforms the keypress is signaled through, in others it isn't. You can try binding to other events like keyup or keypress, some may be signaled even when using an IME.

    The best you can do is to make sure you're not depending on keypress events and have fallback options if you can't intercept them; e.g. bind to change events on the text field as well and handle entire text changes, which will be triggered at the end of the IME input.

    0 讨论(0)
提交回复
热议问题