Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript to allow only numbers, comma, dot, backspace

i wrote a javascript function to allow only numbers, comma, dot like this

function isNumber(evt) {
              var theEvent = evt || window.event;
              var key = theEvent.keyCode || theEvent.which;
              key = String.fromCharCode(key);
              var regex = /^[0-9.,]+$/;
              if (!regex.test(key)) {
                  theEvent.returnValue = false;
                  if (theEvent.preventDefault) theEvent.preventDefault();
              }

}

but if i want to remove any number form text box.. backspace is not working. then i changed regex code as "var regex = /^[0-9.,BS]+$/;"

still i am not able to use backspace in textbox.even i cant use left and right keys on textbox is i am doing wrong? can anyone help... thanks. (when I used "BS" in regex instead of backspace its allowing "B","S" Characters in textbox..)

like image 798
vishnu reddy Avatar asked Jan 27 '14 06:01

vishnu reddy


1 Answers

Try this code:

function isNumber(evt) {
          var theEvent = evt || window.event;
          var key = theEvent.keyCode || theEvent.which;
          key = String.fromCharCode(key);
          if (key.length == 0) return;
          var regex = /^[0-9.,\b]+$/;
          if (!regex.test(key)) {
              theEvent.returnValue = false;
              if (theEvent.preventDefault) theEvent.preventDefault();
          }
}
like image 110
anubhava Avatar answered Nov 15 '22 01:11

anubhava