24

I'm making a form and would like the code to execute only if the input values are numbers. I'm trying to avoid using some kind of validation plugin and was wondering if there is a way to loop through the input fields and check for the values.

I've been trying the following but I think my logic is wrong:

(#monthlyincome is the form id)

$("#submit").click(function() {

  $("#monthlyincome input").each(function() {

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

       }

   });

});

Any ideas?

This is the whole updated code:

$("#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 is a function for... formatting the numbers. :)

Gangnus
  • 24,044
  • 16
  • 90
  • 149
Alex Berg
  • 747
  • 3
  • 8
  • 17
  • 1
    Haven't checked this, but it just popped into my head.. If you're doing an each() on all input elements, that will most likely include the submit button too, so it will check the value of your submit and fail if that's not a number. Haven't tested this, but seems logical;) Also the code there is not closed correctly, but that might be just a copy+paste error. – Sondre Jan 21 '11 at 11:33
  • 1
    @Sondre, I was thinking that as well, but he could (and should) be using ` – David Tang Jan 21 '11 at 11:35
  • @Sondre: I've been trying using a class (which only corresponds to a few input fields) with the same (negative) result. The closing was indeed a copy paste error. :P @Box9: I'm not using button actually but it still won't work even if I use $(".classname").each(). – Alex Berg Jan 21 '11 at 11:39
  • @Box9 Ye, using any other type of element for submitting should fix it. Or targeting specific input types like input[type=text] as it's most likely only textfields you want to check anyways. Not much point doing that check on a radiobutton;) – Sondre Jan 21 '11 at 11:40
  • @Alex Berg Added some code I tested as an answer. That code should work so you can compare it to yours and maybe you find the difference – Sondre Jan 21 '11 at 11:57
  • @Alex actually it would be more helpful if you posted that form because (if I understand you correctly?) the error occurs before you reach the code inside the if-statement. So it must have something to do with how jquery loops through the form – Sondre Jan 21 '11 at 12:25
  • @Sondre: I uploaded the whole form here http://pastebin.com/6HFf5su5 to avoid making this post too long. – Alex Berg Jan 21 '11 at 12:36
  • 1
    @Alex Berg Ok you can test this and maybe you'll be able to adapt this function to your own. http://pastebin.com/UajaEc2e is my suggestion to a simple check for you form. Hope this can be of some help mate:) Seperated your form into two forms, where one is the fields that can be filled, while the other is the readonly part where the result seems to be pasted in. This to avoid the form validation trying to touch the readonly part that as far as I can see don't need to be validated as it's data provided from your calculations that should be set there. – Sondre Jan 21 '11 at 13:04
  • @Sondre: Great! Actually, it works without separating the forms.Maybe including the whole processing part in the each() function messed things up. Please paste it here so I can vote it as an answer. Thanks again. – Alex Berg Jan 21 '11 at 13:20

3 Answers3

41

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Sondre
  • 1,878
  • 18
  • 33
  • I'm banging my head against the wall here. Your code works of course and I can't find any difference with mine but my code still won't work... – Alex Berg Jan 21 '11 at 12:07
  • @Alex well, not much more I can help you with without seeing more of your code then.. Most likely some stupid error you'll laugh about once you find it;) – Sondre Jan 21 '11 at 12:12
  • Haha most likely... I'll actually update with the whole code block and if you got some time, feel free to check it out. – Alex Berg Jan 21 '11 at 12:13
1

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
}
RoToRa
  • 37,635
  • 12
  • 69
  • 105
0

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>