正则表达"。"在文本框的按键上

时间:2013-01-23 07:20:58

标签: javascript regex events keypress

嗨我有一个Key press的Javascript代码,我想放“。”和文本框上的数字。我可以输入数字而不是“。”。我有Javascript和HTMl以及Fiddle链接。任何人都可以帮我吗?

<script>
    var aa_zChar = new Array(' ');
    var aa_maxphonelength = 8;
    var aa_phonevalue1;
    var aa_phonevalue2;
    var aa_cursorposition;
    function aa_ParseForNumber1(object){
      aa_phonevalue1 = aa_ParseChar(object.value, aa_zChar);
    }
    function a_ParseForNumber2(object){
      aa_phonevalue2 = aa_ParseChar(object.value, aa_zChar);
    }
    function aa_up(object,e) { 
      if(e){ 
        e = e 
      } else {
        e = window.event 
      } 
      if(e.which){ 
        var keycode = e.which 
      } else {
        var keycode = e.keyCode 
      }
      aa_ParseForNumber1(object)

        aa_ValidatePhone(object)

    }
    function aa_down(object,e) { 
      if(e){ 
        e = e 
      } else {
        e = window.event 
      } 
      if(e.which){ 
        var keycode = e.which 
      } else {
        var keycode = e.keyCode 
      }
      aa_ParseForNumber2(object)
    } 

    function aa_ValidatePhone(object){
      var p = aa_phonevalue1
      p = p.replace(/[^\d]*/gi,"") 
        object.value=p


    }

    function aa_ParseChar(sStr, sChar)
    {
      if (sChar.length == null) 
      {
        aa_zChar = new Array(sChar);
      }
        else aa_zChar = sChar;
      for (i=0; i<aa_zChar.length; i++)
      {
        sNewStr = "";
        var iStart = 0;
        var iEnd = sStr.indexOf(sChar[i]);
        while (iEnd != -1)
        {
          sNewStr += sStr.substring(iStart, iEnd);
          iStart = iEnd + 1;
          iEnd = sStr.indexOf(sChar[i], iStart);
        }
        sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);
        sStr = sNewStr;
      }
      return sNewStr;
    }
    </script>

HTML

<input name="name" type="text" maxlength="100" id="name" value="" onKeyDown="aa_down(this,event);" onKeyUp="aa_up(this,event);" />

http://jsfiddle.net/4emDC/2/

1 个答案:

答案 0 :(得分:2)

几乎就在那里。您只需要更改正则表达式,以便它接受.和数字。 其中一个正确的正则表达式是/[^\d.]/gi