Validating the form field

Asked

Viewed 51 times

1

I’m creating a simple form, in which I have to make 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 more dynamic way, not just copy the same script over and over again. Follow my code below

<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>
  • I advise you to use a form validation lib I can advise you to use http://formvalidation.io/examples/ see the examples and documentation

1 answer

2


3 remarks:

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

You don’t want to tie in ids why they should be unique, so it makes no sense to loop into a single element. If you delete the .each of your code will see that the result is the same.

2) event.preventDefault();

I saw no use in that preventDefault(). The event change is not cancellable. This method should only be used for events cancellable (as click and Submit, for example).

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

It makes no sense to use classes with different names just to be able to locate the element. In the code below you won’t even need to classify these elements because you can locate the span with .next(), since the span is the element just after the field $("#consultores[n]").

As for the code, you can do it this way (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
   }
});

Working:

$('[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>
<script src="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>

  • But the result is?

  • calculating

  • rsrs... ixi maria! Rs... he wants a single function that does the calculations and insert the phrase "worked" in the respective span... a pois, aí aí na resposta uma solução :D

  • $(this). next(). html("worked out and the value is "+calculus)

  • Why all those libraries? jquery is enough

  • It is vdd, question limits and zefini. Dai only of pirraça will not score as accepted, rs

  • The libraries to look good

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.