Validating form field

1

I am creating a simple form, in which I have to do a calculation of two fields to appear a message, until then no problem, but since there are several fields that I will have to apply the same formula several times, I wanted to do it in a way dynamic, not just copying the same script multiple times. Below is my code

<div class="col-4">
    <label for="habitantes" class="label">Número de Habitantes:</label>
    <input type="number" name="habitantes" id="habitantes">
</div>
<div class="col-4">
    <label for="habitantes2" class="label">Número de Habitantes:</label>
    <input type="number" name="habitantes2" id="habitantes2">
</div>
<div class="col-4">
    <label for="consultores" class="label">Número de Consultores Cadastrados</label>
    <input type="number" name="consultores[]" id="consultores">
    <span style="color:green" class="resultado"></span>
</div>
<div class="col-4">
    <label for="consultores2" class="label">Número de Consultores Cadastrados</label>
    <input type="number" name="consultores[]" id="consultores2">
    <span style="color:green" class="resultado2"></span>
</div>

<script>
$('#consultores').change(function(event) {
        event.preventDefault();
        $('#consultores').each(function() {
            var valor = $('#habitantes').val();
            var valor2 = $('#consultores').val();
            var calculo = valor / valor2;
            if(calculo>=100){
                $('.resultado').html("deu certo");  
            }
        });
     });

    $('#consultores2').change(function(event) {
        event.preventDefault();
        $('#consultores').each(function() {
            var valor = $('#habitantes2').val();
            var valor2 = $('#consultores2').val();
            var calculo = valor / valor2;
            if(calculo>=100){
                $('.resultado2').html("deu certo"); 
            }
        });
     });
<script>
    
asked by anonymous 08.06.2018 / 19:01

1 answer

3

3 comments:

1) $('#consultores').each(function() {

You will not want to loop in id s because they must be unique, so do not feel like looping on a single element. If you delete .each from your code you will see that the result is the same.

2) event.preventDefault();

I did not see utility in this preventDefault() . The change event is not cancellable . This method should only be used in cancelable events such as click and submit , for example).

3) class="resultado" and class="resultado2"

It does not make sense to use classes with different names just to be able to locate the element. In the code below you will not even need to put class in these elements because you can find span with .next() , since span is the element just after the $("#consultores[n]") field.

As for the code, you can do this (see explanations in the code):

$('[id^="consultores"').change(function(){ // escuta os campos que possuem id começando com a palavra "consultores"

   var idx = $(this).attr("id").match(/\d+/); // pego apena a parte numérica da id
   idx = idx ? idx[0] : ''; // verifica se existe parte numérica. Se existe, pega, se não, retorna vazio

   var valor = $('#habitantes'+idx).val(); // concateno o idx para pegar o #habitantes + número
   var valor2 = $(this).val();  // pego o próprio valor do elemento alterado
   var calculo = valor / valor2;
   if(calculo>=100){
       $(this).next().html("deu certo"); // pego o elemento próximo e insiro o texto
   }
});

Running:

$('[id^="consultores"').change(function(){
   
   var idx = $(this).attr("id").match(/\d+/);
   idx = idx ? idx[0] : '';
   
   var valor = $('#habitantes'+idx).val();
   var valor2 = $(this).val();
   var calculo = valor / valor2;
   if(calculo>=100){
       $(this).next().html("deu certo");  
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

<div class="col-4">
    <label for="habitantes" class="label">Número de Habitantes:</label>
    <input type="number" name="habitantes" id="habitantes">
</div>
<div class="col-4">
    <label for="habitantes2" class="label">Número de Habitantes:</label>
    <input type="number" name="habitantes2" id="habitantes2">
</div>
<div class="col-4">
    <label for="consultores" class="label">Número de Consultores Cadastrados</label>
    <input type="number" name="consultores[]" id="consultores">
    <span style="color:green"></span>
</div>
<div class="col-4">
    <label for="consultores2" class="label">Número de Consultores Cadastrados</label>
    <input type="number" name="consultores[]" id="consultores2">
    <span style="color:green"></span>
</div>
    
08.06.2018 / 19:36