javascript - capture input and convert characters

后端 未结 3 1014
谎友^
谎友^ 2021-01-06 13:07

I want to capture input charcters in text box, convert then according to a table and put them back in text box as user types.

Ent
相关标签:
3条回答
  • 2021-01-06 13:13

    Should do the trick. Now works wherever caret is and even when you copy/paste WECZ into field (if that matters)

    var conversionMap = {W:1,E:2,R:3,S:4,D:5,F:6,Z:7,X:8,C:9};
    function alphaToNum(){
        var field = document.getElementById('idMyText');
        var value = field.value.split('');
        var i = 0, len = value.length;
    
        for(i;i<len;i++){
            if (conversionMap[value[i]]) {
                value[i] = conversionMap[value[i]];
            }
        }
        field.value = value.join('');
        // prevent memory leak.
        field = null;
    }
    

    its working good until we didn't use utf-8 chars like öéáí etc... any idea for repair this "leak" ?

    0 讨论(0)
  • 2021-01-06 13:14

    Should do the trick. Now works wherever caret is and even when you copy/paste WECZ into field (if that matters)

    var conversionMap = {W:1,E:2,R:3,S:4,D:5,F:6,Z:7,X:8,C:9};
    function alphaToNum(){
        var field = document.getElementById('idMyText');
        var value = field.value.split('');
        var i = 0, len = value.length;
    
        for(i;i<len;i++){
            if (conversionMap[value[i]]) {
                value[i] = conversionMap[value[i]];
            }
        }
        field.value = value.join('');
        // prevent memory leak.
        field = null;
    }
    

    ** Edit after Tim Downs comment **

    0 讨论(0)
  • 2021-01-06 13:32

    It might be better to do this when the value changes in the input, rather than when the key is pressed. Otherwise, other forms of input (pasting value) will bypass this substitution.

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