如何将文本框的值转换为数字

我想问问.我如何开始对此进行编码?
我想将TextBox的值转换为数字.
例如,TextBox的值为"box"
而且每个字母都有正确的值.
B=1
O=3
X=2
...诸若此类.
嗯,我可以用Java脚本或php制作吗?

# 回答1


如果您希望在用户将内容键入文本"框"时进行转换,则必须使用JavaScript.如果希望在用户向服务器提交表单时进行转换,则必须使用php
下面是一个使用onChange()事件处理程序更改内容的js脚本.您可以使用regExp使其更快.或者,您甚至可以在用户使用onkeypress()事件处理程序键入每个字符时对其进行转换.

选择 | 换行 | 行号
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <head>
  4.         <script type="text/javascript">
  5.             function convertTxtBox(obj){
  6.  
  7.                 //capture the id and value of the control element being processed
  8.                 var elm = obj.id;
  9.                 var val = obj.value;
  10.  
  11.                 //create an object with conversion values
  12.                 lookup = {b:1, o:3, x:2};
  13.  
  14.                 //initilize return value
  15.                 var retVal = '';
  16.  
  17.                 //loop through each letter in text box and convert
  18.                 for (var i = 0, l = val.length; i < l; i++) {
  19.  
  20.                     //get the current charcter in the string
  21.                     var re = val[i];
  22.  
  23.                     //replace numeric value found in lookup object or return same character if not found
  24.                     retVal += ( lookup[re] ) ?lookup[re] : re;
  25.                 }
  26.                 //replace the text box value with converted value
  27.                 document.getElementById(elm).value = retVal;
  28.             }
  29.         </script>
  30.     </head>
  31.     <body>
  32.         <input type="text" id="txtBox" onchange="convertTxtBox(this);"/>
  33.     </body>
  34. </html>
  35.  
# 回答2


感谢你的帮助..

标签: Javascript

添加新评论