Jquery - Text field with numeric text

I found this very short clean code to allow only numeric characters in a text box. Currently, it only covers numbers 0-9 and vice versa and deletes. I wanted it to also include the decimal / period, so I struggled with this by simply including the code 110 and / or 190. I can't get it to work. Can anyone see what I'm doing wrong?

$(document).ready(function() { $('input.numberinput').bind('keypress', function(e) { return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57) ) || (e.which!=110) ? false : true ; }); }); 

jsfiddle here : http://jsfiddle.net/justmelat/EN8pT/

HTML

  <div class="label">Enter a number:</div> <input type="text" name="txtNumber1" id="txtNumber1" value="" class="numberinput" /> <div class="label">Enter a number:</div> <input type="text" name="txtNumber2" id="txtNumber2" value="" class="numberinput" /> </div> 
+4
source share
3 answers

Try:

 $(document).ready(function () { $('input.numberinput').bind('keypress', function (e) { return !(e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && e.which != 46); }); });​ 

JsFiddle : http://jsfiddle.net/EN8pT/1/

+6
source

With the answer above, you can still do 0.23.12.33, which is not a valid number.

http://www.texotela.co.uk/code/jquery/numeric/ is a very small lightweight plugin that I have used a lot. This eliminates the pain from the above.

+1
source
 $("#input").keydown(function(event) { var theEvent = event || window.event; var key = theEvent.keyCode || theEvent.which; // Allow: backspace, delete, tab, escape, and enter if ( key == 46 || key == 8 || key == 9 || key == 27 || key == 13 || key == 110 || key == 190 || // Allow: Ctrl+A (key == 65 && theEvent.ctrlKey === true) || // Allow: home, end, left, right (key >= 35 && key <= 39)) { // let it happen, don't do anything return; } else { // Ensure that it is a number and stop the keypress if (theEvent.shiftKey || (key < 48 || key > 57) && (key < 96 || key > 105 )) { theEvent.preventDefault(); } } }); 

with code code 110 and 190

0
source

All Articles