jquery 数值输入框实现

页面上引入这段js,监听了文本keyup与blur事件,参照easyui写的,文本框初始化时没做数值验证,有兴趣的人参照下面blur事件实现

 

<input type="text" class="ll-numberbox" data-options="min:0.1,max:999,precision:2" value="" />

 

//数值输入框格式化
String.prototype.endWith = function(str) {
  if (str == null || str == "" || this.length == 0 || str.length > this.length)
    return false;
  if (this.substring(this.length - str.length) == str)
    return true;
  else
    return false;
  return true;
}
String.prototype.startWith = function(str) {
  if (str == null || str == "" || this.length == 0 || str.length > this.length)
    return false;
  if (this.substr(0, str.length) == str)
    return true;
  else
    return false;
  return true;
}
String.prototype.trim = function() {
  return this.replace(/(^\s*)|(\s*$)/g, '');
};
$(function() {
  $("body").on("keyup", ".ll-numberbox", function(e) {
    if(e.which == 8 || e.which == 0 || (e.which >= 48 && e.which <= 57 && e.ctrlKey == false && e.shiftKey == false)) {
      return false;
    }
    var t_v = $(this).val().trim().replace(/[^\d\.\-]/g, '');
    $(this).val(t_v);
  })
  
  $("body").on("blur", ".ll-numberbox", function(e) {
    var options = $(this).attr("data-options").split(",");
    var t_v = $(this).val().trim().replace(/[^\d\.\-]/g, '');
    if (t_v == '') {
      $(this).val(t_v);
      return false;
    }
    
    if(t_v.startWith(".")) {
      t_v = "0" + t_v;
    }

    var a1, a2;
    var sp = t_v.split(".");
    if (sp.length >= 2) {
      a1 = sp[0];
      a2 = sp[1];
    } else {
      a1 = sp[0];
      a2 = '00';
    }
    t_v = a1 + "." + a2;

    var min, max, precision = 0;// 最小值,最大值,小数位

    for (var i = 0; i < options.length; i++) {
      if (options[i].startWith("min:"))
        min = options[i].replace("min:", "");
      if (options[i].startWith("max:"))
        max = options[i].replace("max:", "");
      if (options[i].startWith("precision:"))
        precision = parseInt(options[i].replace("precision:", ""));
    }
    if (parseFloat(t_v) - parseFloat(min) < 0) {
      t_v = min;
    }
    if (parseFloat(t_v) - parseFloat(max) > 0) {
      t_v = max;
    }

    t_v = parseFloat(t_v).toFixed(precision)
    $(this).val(t_v);
  })
})

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值