且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何防止用户输入小数?

更新时间:2023-12-02 11:14:16

拦截字段的关键事件,输入,防止它们进入字段,并在字段(插入到页面中)附近添加一个临时信息,以解释允许使用哪些字符或值。弹出警报是在打字过程中提供反馈的好方法。

然后,在提交之前再次验证,因为还有其他方法可以将数据导入字段(拖/下载,复制/粘贴等...),你可能没有抓到任何东西。

这里是一个jQuery示例,仅包含整数和只包含小数的字段显示无效键输入时显示的消息:



工作jsFiddle: http:// jsfiddle .net / jfriend00 / CkDTy /

  $(。integer).presspress(function(e){ 
if(e.which< 48 || e.which> 57){
showAdvice(this,Integer values only);
return(false);
}
}); (e){
// 46是句点
if(e.which!= 46&&(( (这是仅十进制数);
return(false);
}
如果(例如== 46&& this.value.indexOf(。)!= -1){
showAdvice(这,在十进制数中只允许一个周期);
return(false); //只允许使用一个小数
}
});

函数showAdvice(obj,msg){
$(#singleAdvice)。stop(true,false).remove();
$('< span id =singleAdviceclass =advice>'+ msg +'< / span>')。
$(#singleAdvice)。delay(4000).fadeOut(1500);
}


I've got an order page on my site. Some order items can have decimal quantities, some can't.

What's the best way to prevent the user from entering decimal quantities? (Apart from an alert box and setting the field to zero)?

Intercept key events for the field, detect illegal characters upon input, keep them from getting entered in the field and add a temporary msg near the field (inserted into the page) that explains what characters or values are allowed. pop up alerts are a bad way to give feedback in the middle of typing.

Then, validate again before submission because there are other ways to get data into fields (drag/drop, copy/paste, etc...) that you might not have caught everything.

Here's a jQuery example of both an integer only and a decimal only field with temporary messages displayed when invalid keys are typed:

Working jsFiddle: http://jsfiddle.net/jfriend00/CkDTy/

$(".integer").keypress(function(e) {
    if (e.which < 48 || e.which > 57) {
        showAdvice(this, "Integer values only");
        return(false);
    }
});

$(".decimal").keypress(function(e) {
    // 46 is a period
    if (e.which != 46 && (e.which < 48 || e.which > 57)) {
        showAdvice(this, "Decimal numbers only");
        return(false);
    }
    if (e.which == 46 && this.value.indexOf(".") != -1) {
        showAdvice(this, "Only one period allowed in decimal numbers");
        return(false);   // only one decimal allowed
    }
});

function showAdvice(obj, msg) {
    $("#singleAdvice").stop(true, false).remove();
    $('<span id="singleAdvice" class="advice">' + msg + '</span>').insertAfter(obj);
    $("#singleAdvice").delay(4000).fadeOut(1500);
}