Looping through input fields for validation using Jquery each()

我的梦境 提交于 2019-12-01 02:11:34
Sondre

Well testing here this works just fine:

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

on a form looking like this:

<form method="post" action="" id="myForm">
    <input type="text" value="1234" />
    <input type="text" value="1234fd" />
    <input type="text" value="1234as" />
    <input type="text" value="1234gf" />
    <input type="submit" value="Send" id="submit" />
</form>

Move the return false around as you see fit

Edit: link to code sdded to OPs form http://pastebin.com/UajaEc2e

The value is a string. You need to try to convert it to a number first. In this case a simple unitary + will do the trick:

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

Based on Sondre (Thank you! Sondre) example above, I developed a sample in Fiddle so that Folks can understand much better to implement

Example: Click Here

$("#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;
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form method="post" action="" id="myForm">
  <input type="text" class="partialProdAmt" value="0" />
  <input type="text" class="partialProdAmt" value="0" />
  <input type="text" class="partialProdAmt" value="0" />
  <input type="text" class="partialProdAmt" value="0" />
  <input type="button" value="Send" id="submit" />
</form>
<div class="msg"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!