【问题标题】:Jquery Masked Input plugin allow dotJquery Masked Input 插件允许点
【发布时间】:2012-10-29 04:26:50
【问题描述】:

我正在使用 JQuery Masked 输入插件。

$("#percent").mask("99.99?9");

这允许像10.999, 10.99, 01.999, 01.99这样的数字

我想要实现的是我不希望用户输入01.99。相反,如果用户键入1.99,我希望在1 之前自动添加0。这就是我开始但不知道如何继续的方式:

  //assume i typed in field 11.99
  $(document).on('keyup', '#percent', function(evt) {
    var input = $(this).val();
    alert(input); // 11.99_
    if(evt.which == '190' || evt.which == '110') {
       //if dot is clicked 
       alert(parseInt(input)); // 11
    }
});

请注意,由于第三个值是可选的,我没有输入,因此警报输入会在末尾打印 11.99_ 并带有下划线。

现在这个值是完全正常的,但如果用户输入1.99,将无法使用,因为它会自动将9 移动到1 以用2 数字填充它,因此它将返回为19.9这是无效的,因为必须有上面定义的 2 小数。因此,在我的 if 语句中,我希望能够检测输入的内容是否小于10,如果小于10(以小数点表示),则在开头添加0

好的,我找到了underscore _ 的修复方法:

    $("#percent").mask("99.99?9", {placeholder: ""})

但仍然无法解决输入1.9919.9 的其他问题

【问题讨论】:

  • 1 之前的零在数字中没有意义,但如果它是数字并且您将其转换为字符串,您真正需要的是 if (input<10) input = '0'+input; 添加前导零.在您的情况下,这将涉及对数字进行一些拆分和解析以使其正确。作为旁注,从输入返回的值始终是字符串。
  • 是的,但我想更改字段,以便屏蔽输入不会消失。如果给出无效的内容,屏蔽的输入就会消失。
  • 你不能用掩码插件做到这一点。我建议你使用正则表达式作为验证器
  • 我想看小提琴...jsfiddle.net

标签: javascript jquery jquery-plugins jquery-events maskedinput


【解决方案1】:

您可以拦截 keydown 来执行此操作,但您需要一些方法来刷新插件状态。

以下代码将起作用:

$("#percent").bind({
    keydown: function(e) {
        // custom handler for dot
        var userInput = parseFloat($("#percent").val());
        if(e.which == '190' || e.which == '110') {
            // if entered number is integer and less than 10
            if(userInput % 1 === 0 && userInput < 10) {
                // prevent default mask input handlers from calling
                e.preventDefault();
                e.stopImmediatePropagation();

                // update value
                $("#percent").val('0'+userInput+'.');

                // simulate paste event to refresh mask input plugin state
                $("#percent").trigger('paste').trigger('input');
            }
        }       
    }
}).mask("99.99?9", {placeholder: ""});

工作 JSFiddle here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 2012-07-22
    相关资源
    最近更新 更多