如何防止用户输入小数? [英] How to prevent user from entering decimals?

查看:140
本文介绍了如何防止用户输入小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有订单页面。一些订单商品可以有小数量,有些则不能。

防止用户输入小数的最佳方法是什么? (除了一个警告框并将字段设置为零)?

解决方案

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

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



这里是一个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);
}

这篇关于如何防止用户输入小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆