简体   繁体   English

如何在html中创建一个文本框以使用jquery只接受实数?

[英]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.在数字之间,这不是数字。

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

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.用输入的 id 替换#idname

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM