help with form calculation

Asked

Viewed 452 times

2

My first problem is that I have a select id "T4" which is multiplied by the dial input so far everything well works but I have to limit the result according to the value of select for example if I select 0.50 and enter in the input any number that result can not exceed 2.00 as well as 0.25 can not exceed 1.00 and 0.20 exceed 0.80.

My second problem is to make appear in the input id "total1a" the result of the sum between the fields dial1a until dial7a as they appear.

Follow my code below:

    <script src="js/jquery-1.7.1.js"></script>
<script language="javascript">




$(window).load(function(){
            // Somente numeros
        $('.nr').keyup(function() {
    var valor = $(this).val().replace(/[^0-9]+/g,'');
            $(this).val(valor);
        });

$("#disc1a").keyup(function(){

    var quantidade = $(this).val();
    var valor      = $("#t1").val();
    var soma = "";
            if ((quantidade != "") && (valor != "")){

            soma = (parseFloat(valor) * parseInt(quantidade));

            if(isNaN(soma)){    
                soma = "";    
            }else{

                soma = soma.toFixed(2);    
            }    
        }       
    $("#promo1a").val(soma);
});
$("#disc2a").keyup(function(){

    var quantidade = $(this).val();
    var valor      = $("#t2").val();
    var soma = "";
            if ((quantidade != "") && (valor != "")){

            soma = (parseFloat(valor) * parseInt(quantidade));

            if(isNaN(soma)){    
                soma = "";    
            }else{    
                soma = soma.toFixed(2);    
            }    
        } 
    $("#promo2a").val(soma);
});

$("#disc3a").keyup(function(){

    var quantidade = $(this).val();
    var valor      = $("#t3").val();
    var soma = "";
            if ((quantidade != "") && (valor != "")){

            soma = (parseFloat(valor) * parseInt(quantidade));

            if(isNaN(soma)){

                soma = "";

            } if ((soma < "1.50")){

            soma = soma.toFixed(2); 

            }else{

            soma = "1.50";  

            }

        }


    $("#promo3a").val(soma);
});


$("#t4").change(function(){

    var quantidade = $(this).val();
    var valor      = $("#disc4a").val();
    var soma = "";

            if ((quantidade != "") && (valor != "")){

            soma = (parseFloat(quantidade) * parseInt(valor));

            if(isNaN(soma)){

                soma = "";

            }else{

                soma = soma.toFixed(2);

            }

        }


    $("#promo4a").val(soma);
});


});  

function calcula(){
        var valor = 0; 

        $('.soma').each(function(i){ 

            valor = parseFloat($(this).val()) + valor ;
            });


        valor = valor.toFixed(2);

        $('#total1a').val( valor );

    }
</script>

<link href="tema/css/info.css" rel="stylesheet" type="text/css">


<table class='wrapper' width="800" cellspacing='1' cellpadding='2' >

    <tr>
      <td width="205" colspan="4" rowspan="2" align="center" class="row1">DADOS APURADOS</td>
      <td width="56" rowspan="2" align="center" class="row1">VALOR</td>
      <td rowspan="2" class="row1" align="center">DISCRIMINAÇÃO</td>
      <td colspan="2" class="row1" align="center">SEM/PROM</td>
    </tr>
    <tr>
      <td width="29" class="row2"><input name="sem1" type="text" id="sem1" size="1"></td>
      <td width="53" class="row2"><input name="semdt1" type="text" id="semdt1" value="<?php echo date('Y') ?>" size="3"></td>
    </tr>
    <tr>
      <td width="205" rowspan="7" class="row1" align="center">P<br /> O <br />N <br />T <br />O <br />S <br /><br /><br />
        P<br />
        O<br />
        S<br />
        I<br />
        T<br />
        I<br />
        V <br />
        O<br />
      S</td>
      <td width="205" rowspan="4" align="center" class="row1">TEMPO<br />DE<br />SERVIÇO</td>
      <td colspan="2" class="row3">FUNÇÃO </td>
      <td class="row3">
      <input name="t1" type="text" disabled="disabled" id="t1" value="0.10" size="5"></td>
      <td width="45" class="row3"><input name="disc1a" type="text" id="disc1a" class="nr" size="9"></td>
      <td colspan="2" class="row3"><input name="promo1a" type="text" id="promo1a" class="soma" size="12"></td>
    </tr>
    <tr>
      <td colspan="2" class="row2">PERMANÊNCIA </td>
      <td class="row2">
      <input name="t2" type="text" disabled="disabled" id="t2" value="0.20" size="5"></td>
      <td class="row2"><input name="disc2a" type="text" id="disc2a" class="nr" size="9"></td>
      <td colspan="2" class="row2"><input name="promo2a" type="text" id="promo2a" class="soma" size="12"></td>
    </tr>
    <tr>
      <td colspan="2" class="row3">INSTRUTOR</td>
      <td class="row3"><input name="t3" type="text" disabled="disabled" id="t3" value="0.25" size="5"></td>
      <td class="row3"><input name="disc3a" type="text" id="disc3a" class="nr" size="9"></td>
      <td colspan="2" class="row3"><span class="row2">
        <input name="promo3a" type="text" id="promo3a" class="soma" size="12">
      </span></td>
    </tr>
    <tr>
      <td colspan="2" class="row2">FUNÇÃO</td>
      <td class="row2"><select name="t4" id="t4">
        <option selected="selected">SELECIONE</option>
        <option value="0.50">EM 0.50</option>
        <option value="0.25">GCG 0.25</option>
        <option value="0.20">DIRETORIA 0.20</option>
      </select></td>
      <td class="row2">
        <input name="disc4a" type="text" id="disc4a" class="nr" size="9">
      </td>
      <td colspan="2" class="row2"><input name="promo4a" type="text" id="promo4a" size="12"></td>
    </tr>
    <tr>
      <td colspan="3" class="row3">APROVEITAMENTO</td>
      <td class="row3"><input name="fer" type="text" disabled="disabled" id="fer" value="0.15" size="5"></td>
      <td class="row3"><input name="disc5a" type="text" id="disc5a" size="9"></td>
      <td colspan="2" class="row3"><span class="row2">
        <input name="promo5a" type="text" id="promo5a" size="12">
      </span></td>
    </tr>
    <tr>
      <td rowspan="2" class="row1">TRABALHOS</td>
      <td colspan="2" class="row2">CATEGORIA &quot;A&quot;</td>
      <td class="row2"><input name="tab1" type="text" disabled="disabled" id="tab1" value="0.50" size="5"></td>
      <td class="row2"><span class="row3">
        <input name="disc6a" type="text" id="disc6a" size="9">
      </span></td>
      <td colspan="2" class="row2"><input name="promo6a" type="text" id="promo6a" size="12"></td>
    </tr>
    <tr>
      <td colspan="2" class="row3">CATEGORIA &quot;B&quot;</td>
      <td class="row3"><input name="tab2" type="text" disabled="disabled" id="tab2" value="0.10" size="5"></td>
      <td class="row3"><input name="disc7a" type="text" id="disc7a" size="9"></td>
      <td colspan="2" class="row3"><span class="row2">
        <input name="promo7a" type="text" id="promo7a" size="12">
      </span></td>
    </tr>
    <tr>
      <td colspan="6" class="row3" align="right">(1) SOMA DOS PONTOS POSITIVOS</td>
      <td colspan="2" class="row3"><span class="row2">
        <input name="total1a" type="text" id="total1a" onkeyup="up(this)" onblur="calcula();" size="12">
      </span></td>
    </tr>
</table>

made a sample for better visualization of the problem

https://jsfiddle.net/opeta/38av49L9/8/

2 answers

2

You can summarize quite a lot of your code making it more generic, this way:

<td class="row3">
  <input name="t1" type="text" disabled="disabled" id="t1" value="0.10" size="5">
</td>
<td width="45" class="row3">
  <input data-operator="#t1" data-result="#promo1a" name="disc1a" type="text" id="disc1a" class="nr" size="9">
</td>
<td colspan="2" class="row3">
  <input name="promo1a" type="text" id="promo1a" class="soma" size="12">
</td>

note that you add two attributes data-operator and data-result thus it is possible to indicate which element is the quantity (operand) and which element is the result. Following this same idea we can do the following:

$('.nr').keyup(function() {
  var valor = $(this).val().replace(/[^0-9]+/g,'');
  $(this).val(valor);

  var quantidade = $($(this).data("operator")).val(); //pega a quantidade o elemento indicado
  valor = (parseFloat(valor) * parseFloat(quantidade));

  if(!isNaN(valor)){
    //teste específico para o elemento #t4
    if($($(this).data("operator")).attr("id") == "t4"){
      if((quantidade == 0.5) && (valor <= 2)){
        $($(this).data("result")).val(valor.toFixed(2));
      }
      else if((quantidade == 0.25) && (valor <= 1)){
        $($(this).data("result")).val(valor.toFixed(2));
      }
      else if((quantidade == 0.2) && (valor <= 0.8)){
        $($(this).data("result")).val(valor.toFixed(2));
      }
      else $($(this).data("result")).val(0.00); //extrapolou
    }
    //outros elementos
    else $($(this).data("result")).val(valor.toFixed(2)); 
  }
  else $($(this).data("result")).val(0.00); //coloquei zero caso não seja um número

  //calcula o total
  calcula();
});

In your function of totaling I would just add one more test:

function calcula(){
  var valor = 0; 

  $('.soma').each(function(){ 
    var testar = parseFloat($(this).val()); 
    if(!isNAN(testar)) valor += testar;
  });

  $('#total1a').val(valor.toFixed(2));  
}

I hope I’ve helped.

  • thank you friend more think the code does not help because the problem is in select that is multiplied by the input that puts the value, it has three values 0.50 that can not exceed 2.00, 0.25 which cannot exceed 1.00 and 0.20 which cannot exceed 0.80 and the totaling function which you modified is not working. The problem with mine is that it only gives the result if I enter and exit the input and I wanted it to be automatic, any more idea?

  • @opeta I still think the answer to the question this there, with a few edits in the code. I will edit it to demonstrate

1


Here’s a code simplification suggestion.

jsFiddle: http://jsfiddle.net/xaqfb1dx/

The idea is to remove an Event Handler for each element and use a generic $("input[id^=disc]").

Making a loop with the each these elements can be used index to associate the input of the column on the side and so do not need to fetch the element from the DOM at each calculation.

The verification that the select accurate, if understood well max 4 times higher, can be done with if (i== 3 && soma > 4 * valor) soma = 4 * valor;, which assigns the maximum value if the value exceeds 4x.

So the code I put in jsFiddle is:

$(window).load(function () {
    // Somente numeros
    $('.nr').keyup(function () {
        var valor = this.value;
        if (valor) this.value = valor.replace(/[^0-9]+/g, '');
    });
    $("input[id^=disc]").each(function (i) {
        var index = i + 1;
        var $tValor = $("#t" + index);
        var $promo = $("#promo" + index + "a")
        $(this).on('keyup', function () {
            var quantidade = this.value;
            var valor = $tValor.val();
            var soma = 0;
            if (quantidade && valor) {
                soma = parseFloat(valor) * parseInt(quantidade);
                if (isNaN(soma)) soma = 0;
                else soma = soma.toFixed(2);
            }
            if (i== 3 && soma > 4 * valor) soma = 4 * valor;
            $promo.val(soma);
            calcula();
        });
    });
    $('#t4').change(function () {
        $('#disc4a').keyup();
    });
});

function calcula() {
    var valor = 0;
    $('.soma').each(function () {
        valor = parseFloat(this.value || 0) + valor;
    });
    $('#total1a').val(valor.toFixed(2));
}
  • perfect friend very thank you could never do without help only the result of select when it reaches the value is coming an integer rather than decimal, without wanting to abuse I will have to do other selects like this explain me how I can limit these values because I did not understand the logic.

  • now I understood the logic more how to apply it for example to the input disc3a where the limit of the points was 1.50 and now ta without this limit, I thank you again for your help freed me of a headache.

  • @I have just seen your comments. If you want you can put a jsFiddle here with the rest of the HTML and I can adapt the code to more selects. Remember to mark as accepted one of the answers.

  • 1

    my friend I want to thank you, I studied your script a lot and I managed to make it work with all the restrictions that the document asked, your logic was just perfect only with a lot of study and dedication I could do. i program a little in php and want to expand my horizons, you suggest me some course or book in php or javascript?

  • @Opeta is putting problems that you have here at Sopt and studying the answers that already exist here. You’ll learn a lot and maybe soon help others too :)

Browser other questions tagged

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