3

我想在文本框中捕获输入字符,然后根据表格进行转换并将它们作为用户类型放回文本框中。

<form id='myForm'>

Enter phone number:<input type="text" id='idMyText' name="myText" onKeyUp="alphaToNum(this.value)">
</form>




<script>
// on each keypress in input box, I want to capture key pressed,
// determine if key pressed belong to group of identified characters
// if, so then convert to specified numeric equivalent and return character 
// to text box.
// This mapping corresponds to numeric characters on blackberry device.
// Normally user has to press alt+letter to get numbers. This will provide
// quicker access to numeric characters on for numeric fields

function alphaToNum(e) {
 x = e;
 x = (x.replace(/W/, "1"));
 x = (x.replace(/E/, "2"));
 x = (x.replace(/R/, "3"));
 x = (x.replace(/S/, "4"));
 x = (x.replace(/D/, "5"));
 x = (x.replace(/F/, "6"));
 x = (x.replace(/Z/, "7"));
 x = (x.replace(/X/, "8"));
 x = (x.replace(/C/, "9")); 
 document.getElementById('idMyText').value = x; 
}

</script> 
4

3 回答 3

6

应该做的伎俩。现在可以在插入符号所在的任何地方工作,即使您将 WECZ 复制/粘贴到字段中(如果重要的话)

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;
}

** 在 Tim Downs 评论后编辑 **

于 2010-10-06T14:37:08.990 回答
0

当输入中的值发生变化而不是按下键时,这样做可能会更好。否则,其他形式的输入(粘贴值)将绕过此替换。

于 2010-10-06T14:24:50.083 回答
0

应该做的伎俩。现在可以在插入符号所在的任何地方工作,即使您将 WECZ 复制/粘贴到字段中(如果重要的话)

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;
}

在我们不使用 öéáí 等 utf-8 字符之前,它工作得很好……有什么办法可以修复这个“泄漏”吗?

于 2015-01-28T10:29:08.697 回答