【问题标题】:Calculation accepts space in input filds计算接受输入字段中的空格
【发布时间】:2014-05-13 20:02:15
【问题描述】:

我有这个脚本来计算表格

    $(".mad, .mad2, .mad3, .mad4, .mad5, .mad6").each(function() {
        //add only if the value is number
        if (!isNaN(this.value) && this.value.length != 0) {
            antal += parseFloat(this.value);
             subtotal = antal*30;
             $(this).css("background-color", "#ffffff");
        }
        else if (this.value.length != 0){
             $(this).css("background-color", "#e89898");
       }
    });
        $("#antal").html(antal.toFixed(0));
        $("#subtotal").html(subtotal.toFixed(0));

如果有人尝试添加一个字母或将其删除并且输入字段变为红色,它似乎工作正常。但是我确实接受空间导致antal和subtotal Show NaN

如何让它同时适用于字母和空格(也不接受空格)?

【问题讨论】:

  • 只用空字符串替换空格:this.value.replace(/ /g,'')
  • 为什么需要else if 中的if?这不应该只是else吗?

标签: javascript jquery


【解决方案1】:

尝试使用 jquery 的 trim() 方法删除所有空格:

if (this.value.trim().length != 0 && !isNaN(this.value.trim()) ) {

}

【讨论】:

  • 谢谢,但是我在脚本中的哪个位置做广告
  • 我猜你想通了?您想用我发布的内容替换您发布的第一个 if 语句。
【解决方案2】:
if (parseFloat(this.value) == this.value) {

【讨论】:

    猜你喜欢
    • 2011-08-29
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 2022-11-30
    • 1970-01-01
    相关资源
    最近更新 更多