javascript - 捕获输入和转换字符 [英] javascript - capture input and convert characters

查看:102
本文介绍了javascript - 捕获输入和转换字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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


推荐答案

应该做的伎俩。
现在适用于插入符号的地方,甚至当你将WECZ复制/粘贴到字段中时(如果这很重要)

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

** Tim Downs评论后编辑**

** Edit after Tim Downs comment **

这篇关于javascript - 捕获输入和转换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆