Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
Recorriendo los campos de entrada para la validación usando Jquery each()

Estoy creando un formulario y me gustaría que el código se ejecute solo si los valores de entrada son números. Estoy tratando de evitar el uso de algún tipo de complemento de validación y me preguntaba si hay una forma de recorrer los campos de entrada y verificar los valores.

He estado intentando lo siguiente, pero creo que mi lógica es incorrecta:

(#monthlyincome es la identificación del formulario)

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

¿Algunas ideas?

Este es todo el código actualizado:

 $("#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 es una función para... dar formato a los números. :)

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Bueno probando aquí esto funciona bien:

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

en un formulario parecido a este:

 <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>

Mueva el retorno falso como mejor le parezca.

Editar: enlace al código incluido en el formulario OPs http://pastebin.com/UajaEc2e

over 4 years ago · Santiago Trujillo Report

0

El value es una cadena. Primero debe intentar convertirlo en un número. En este caso, un + unitario simple hará el truco:

 if (!isNaN(+this.value)) { // process stuff here }
over 4 years ago · Santiago Trujillo Report

0

Basado en el ejemplo anterior de Sondre (¡Gracias! Sondre), desarrollé una muestra en Fiddle para que la gente pueda entender mucho mejor cómo implementar

Ejemplo: Haga clic aquí

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!