-1
$("#chartModal").keypress( function (e) {

  if (e.which != 8 && e.which != 0 && e.which != 43 && e.which != 45 && e.which != 46 && (e.which < 48 || e.which > 57)) {
    return false;
  }
});

This accept +, - & . in between the number, which is not a number.

Hearner
  • 2,711
  • 3
  • 17
  • 34
  • Why don't you just try a parseInt() on your character ? If isNan, -> preventDefault – Superdrac Jun 24 '16 at 10:02
  • Improve your formatting. All lines of code must have be indented by least four spaces. – flaviodesousa Jun 24 '16 at 10:03
  • Possible duplicate of [How to allow only numeric (0-9) in HTML inputbox using jQuery?](http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery) – theblindprophet Jun 24 '16 at 12:29

2 Answers2

1

Try with this

 $(document).ready(function () {
            $('#chartModal').keypress(function(e) {
                var key = e.charCode || e.keyCode || 0;
                var keychar = String.fromCharCode(key);

                if (  ((key == 8 || key == 9 || key == 46 || key == 35 || key == 36 || (key >= 37 && key <= 40)) && e.charCode==0) /* backspace, end, begin, top, bottom, right, left, del, tab */
                        || (key >= 48 && key <= 57) ) { /* 0-9 */
                    return;
                } else {
                    e.preventDefault();
                }
            });
        });
Sabri Tahri
  • 126
  • 1
0

Here is an example:

$('#chartModal').keypress(function(e){
    if (e.which != 8 && e.which != 0 &&e.which!= 43 && e.which!=45 && e.which !=46 &&(e.which < 48 || e.which > 57)) {
        return false;
    }
    var charCode = e.which;
    var value=$(this).val();
    if(charCode==43 && value.indexOf('+')>=0) //Check whether a + is already there at beginning
     return false;
 if (charCode == 45 && value.indexOf('-') >= 0)//Check whether a - is already there at beginning
     return false;
 if (charCode == 46 && value.indexOf('.')!=-1)//Check at least one . is present in the number
     return false;
});

Replace #idname with id of input.