Search code examples
javascripttextbox

How to create a textbox in html to accept only real number using jquery?


$("#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.


Solution

  • 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();
                    }
                });
            });