美文网首页
金额输入框js处理

金额输入框js处理

作者: 你这个锤子 | 来源:发表于2019-06-28 18:26 被阅读0次

目录

<input>标签的type属性跟maxlength属性
金额输入框js处理实例1,2


<input>标签中type属性为numbermaxLength属性会失效;此时只能用 Js 处理输入框值建议事件使用onInputjquery 中 keyuptype值为textmaxLength恢复效果。


页面代码为:<input type="text" id="ipt1" />

实例1 js代码
$("#ipt1").keyup(function () {
    //输入框限制字符长度为10
    var len = $(this).val().length > 10 ? $(this).val().slice(0,10) : $(this).val();
    $(this).val(len);
    var reg = $(this).val().match(/\d+\.?\d{0,2}/);
    var txt = '';
    if (reg != null) {
        //第一个字为零第二个字符不为‘.’
        if(reg[0].substring(0,1) === "0" && reg[0].substring(1,2) !== "."){
            txt = "0"
        } else {
            txt = reg[0];
        }
    }
    $(this).val(txt);
}).change(function () {
    $(this).keypress();
    var v = $(this).val();
    if (/\.$/.test(v)){
        $(this).val(v.substr(0, v.length - 1));
    }
});
实例2
$("#ipt1").keyup(function () {
        var input=$(this).val();
        if(input.length == 0){
            lastAmount=input;
            $(this).val("");
            return
        }
        //输入框限制字符长度为10
        if(input.length > 10){
            $(this).val(input.slice(0,10));
            return
        }
        if(input.match(/^(0|[1-9]\d*)(\.\d{0,2})?$/)){
            lastAmount=input;
        }else{
            $(this).val(lastAmount||'');
        }
    }).change(function () {
        $(this).keypress();
        var v = $(this).val();
        if (/\.$/.test(v)){
            $(this).val(v.substr(0, v.length - 1));
        }
    });

相关文章

网友评论

      本文标题:金额输入框js处理

      本文链接:https://www.haomeiwen.com/subject/yzbecctx.html