使用Jquery each()循环通过输入字段进行validation

我正在创建一个表单,并且只有在输入值是数字时才希望代码执行。 我试图避免使用某种validation插件,并想知道是否有办法循环输入字段并检查值。

我一直在尝试以下但我认为我的逻辑错了:

(#monthlyincome是表单ID)

$("#submit").click(function() { $("#monthlyincome input").each(function() { if (!isNaN(this.value)) { // process stuff here } }); }); 

有任何想法吗?

这是整个更新的代码:

 $("#submit").click(function() { $("#monthlyincome input[type=text]").each(function() { if (!isNaN(this.value)) { // processing data var age = parseInt($("#age").val()); var startingage = parseInt($("#startingage").val()); if (startingage - age > 0) { $("#field1").val(startingage - age); $("#field3").val($("#field1").val()); var inflationyrs = parseInt($("#field3").val()); var inflationprc = $("#field4").val() / 100; var inflationfactor = Math.pow(1 + inflationprc, inflationyrs); $("#field5").val(inflationfactor.toFixed(2)); var estyearlyinc = $("#field6").val(); var inflatedyearlyinc = inflationfactor * estyearlyinc; $("#field7").val(FormatNumberBy3(inflatedyearlyinc.toFixed(0), ",", ".")); var estincyears = $("#field2").val(); var esttotalinc = estincyears * inflatedyearlyinc; $("#field8").val(FormatNumberBy3(esttotalinc.toFixed(0), ",", ".")); var investmentrate = $("#field9").val() / 100; var investmentfactor = Math.pow(1 + investmentrate, inflationyrs); $("#field10").val(investmentfactor.toFixed(2)); var currentsavings = $("#field11").val(); var futuresavings = currentsavings * investmentfactor; $("#field12").val(FormatNumberBy3(futuresavings.toFixed(0), ",", ".")); //final calculations var futurevalue = (1 * (Math.pow(1 + investmentrate, inflationyrs) - 1) / investmentrate); var finalvalue = (1 / futurevalue * (esttotalinc - futuresavings)); $("#field13").val(FormatNumberBy3(finalvalue.toFixed(0), ",", ".")); } // end processing } }); }); 

FormatNumberBy3是用于…格式化数字的函数。 🙂

在这里测试,这很好用:

 $(function() { $("#submit").click(function() { $("#myForm input[type=text]").each(function() { if(!isNaN(this.value)) { alert(this.value + " is a valid number"); } }); return false; }); }); 

在一个看起来像这样的表格上:

 

根据需要移动返回false

编辑:链接到ssded到OPs的代码http://pastebin.com/UajaEc2e

value是一个字符串。 您需要先尝试将其转换为数字。 在这种情况下,一个简单的单一+将做的伎俩:

 if (!isNaN(+this.value)) { // process stuff here } 

基于上面的Sondre(谢谢!Sondre)示例,我在Fiddle中开发了一个示例,以便人们可以更好地理解

示例: 单击此处

 $("#submit").on("click", function() { var isValid = []; var chkForInvalidAmount = []; $('.partialProdAmt').each(function() { if ($.trim($(this).val()) <= 0) { isValid.push("false"); } else { isValid.push("true"); } if ($.isNumeric($(this).val()) === true) { chkForInvalidAmount.push("true"); } else { chkForInvalidAmount.push("false"); } }); if ($.inArray("true", isValid) > -1) { if ($.inArray("false", chkForInvalidAmount) > -1) { $(".msg").html("Please enter Correct format "); return false; } else { $(".msg").html("All Looks good"); } } else { $(".msg").html("Atlest One Amount is required in any field "); return false; } });