Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

javascript - Allowing only numbers and one decimal

Guys and gals i have this piece of JavaScript code that only allows for numbers and one decimal period. The problem i'm having is that when i tab over to my textbox controls it highlights the value but i have press backspace to erase then enter a number. That is an extra keystroke that i want to prevent.

Props to the guy who created it found (http://www.coderanch.com/t/114528/HTML-CSS-JavaScript/decimal-point-restriction) and here is the code. I put this on keyUp event.

 <script>
  // Retrieve last key pressed.  Works in IE and Netscape.
  // Returns the numeric key code for the key pressed.
  function getKey(e)
  {
    if (window.event)
       return window.event.keyCode;
    else if (e)
       return e.which;
    else
       return null;
  }
  function restrictChars(e, obj)
  {
    var CHAR_AFTER_DP = 2;  // number of decimal places
    var validList = "0123456789.";  // allowed characters in field
    var key, keyChar;
    key = getKey(e);
    if (key == null) return true;
    // control keys
    // null, backspace, tab, carriage return, escape
    if ( key==0 || key==8 || key==9 || key==13 || key==27 )
       return true;
    // get character
    keyChar = String.fromCharCode(key);
    // check valid characters
    if (validList.indexOf(keyChar) != -1)
    {
      // check for existing decimal point
      var dp = 0;
      if( (dp = obj.value.indexOf( ".")) > -1)
      {
        if( keyChar == ".")
          return false;  // only one allowed
        else
        {
          // room for more after decimal point?
          if( obj.value.length - dp <= CHAR_AFTER_DP)
            return true;
        }
      }
      else return true;
    }
    // not a valid character
    return false;
  }
</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<input type="text" class="decimal" value="" />

And in Js use this

$('.decimal').keyup(function(){
    var val = $(this).val();
    if(isNaN(val)){
         val = val.replace(/[^0-9.]/g,'');
         if(val.split('.').length>2) 
             val =val.replace(/.+$/,"");
    }
    $(this).val(val); 
});

Check this fiddle: http://jsfiddle.net/2YW8g/

THis worked for me, i have taken this answer from "Nickalchemist" and take none of its credit.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...