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

时间:2016-06-24 09:56:08

标签: javascript textbox

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

这接受+, - &amp; 。在数字之间,这不是数字。

2 个答案:

答案 0 :(得分:0)

试试这个

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

答案 1 :(得分:0)

以下是一个例子:

$('#idname').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;
});

#idname替换为输入ID。