【问题标题】:JQuery 'dot' exception in form [closed]表单中的JQuery“点”异常[关闭]
【发布时间】:2014-07-04 07:16:00
【问题描述】:
$("#rate_of_pay_after_probation").keypress(function (event) {
    //check_numbers(event);
    if (event.which == 8 || event.which == 0) {
        return true;
    }
    if ((event.which < 44 || event.which > 59 || (event.which > 44 && event.which < 48))) {
        return false;
    }
    if (event.which == 44 && $(this).val().indexOf(',') != -1) {
        return false;
    }
});

我可以使用逗号,但说到点我没能做到。

【问题讨论】:

  • 你的问题不清楚,你能解释一下“当谈到 dot 我没能做到”?

标签: jquery input text


【解决方案1】:

如果你只想要浮点数,你可以用这种方式测试它

var regEx= /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;

if(regEx.test($(this).val().replace(',','.').replace(' ',''))) {
    return false;
}

在您的示例中,您可以放入一个函数

function testFloat(value){
     var regEx= /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;

    if(regEx.test(value)) {
        return true; //input is float
    }
    return false;//input is not float
}

然后在你的函数中

$("#rate_of_pay_after_probation").keypress(function (event) {
    //check_numbers(event);
    if (event.which == 8 || event.which == 0) {
        return true;
    }
    if ((event.which < 44 || event.which > 59 || (event.which > 44 && event.which < 48))) {
        return false;
    }
    if (event.which == 44 && testFloat($(this).val().replace(',','.').replace(' ',''))) {
        return false;
    }
});

更新

经过一些解释,我建议你使用这个fiddle(为点添加 event.wich event.which == 46

$("#rate_of_pay_after_probation").keypress(function (event) {
    //check_numbers(event);
    if (event.which == 8 || event.which == 0 || event.which == 46) {
        return true;
    }
    if ((event.which < 44 || event.which > 59 || (event.which > 44 && event.which < 48))) {
        return false;
    }
    if (event.which == 44 && $(this).val().indexOf(',') != -1) {
        return false;
    }
});

【讨论】:

  • 我需要能够同时使用逗号和点,例如:1,200.35。谢谢
  • 所以使用replace(',','')。通过这种方式,您可以删除与评估数字无关的逗号
  • @Comisarul 试着解释一下是什么问题,我可以帮你解决
  • 好吧,我觉得理解有问题。我应该在数据库中注册这个数字,就像这样:1,320.29(法律问题)
  • 当我发现代码编写时,它让我只使用一个逗号。用户不能在表单中添加点。 HTML 输入类型是文本 :)
【解决方案2】:

更改事件类型> keyDown

在这里查看>>http://jsfiddle.net/ChoHongRae/F3KHL/

 $("#rate_of_pay_after_probation").**keydown**(function (event) {
    //check_numbers(event);
    if (event.which == 8 || event.which == 0) {
        //return true;
    }
    if ((event.which < 44 || event.which > 59 || (event.which > 44 && event.which < 48))) {
       // return false;
    }
    if (event.which == 44 && $(this).val().indexOf('.') != -1) {
        alert("dot");
        //return false;
    }

     alert(($(this).val().indexOf('.')));

    if ($(this).val().indexOf('.') != -1) {
        alert("dot");
        return false;
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 2010-10-15
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多