Jquery calculate average and insert the result in the mean field that is disable

0

Good afternoon,

I needed to calculate the average of the values entered in the 4 text boxes, and only to see the result of the average in the average text box after all are filled

HTML

<div class="form-group">                                                
                                            <div class="col-xs-4">
                                            <b>MAT</b>
                                            <input type="text" name="txtMat" id="txtMat" class="form-control media" placeholder="" required>
                                            </div>
                                            <div class="col-xs-4">
                                            <b>C NAT</b>
                                            <input type="text" name="txtCNat" id="txtCNat" class="form-control media" placeholder="" required>
                                            </div>
                                            <div class="col-xs-4">
                                            <b>Média</b>
                                            <input type="text" name="txtMedia" id="txtMedia" class="form-control" placeholder="" disabled required>
                                            </div>                                                                                              
                                        </div>
                                        <div class="form-group">
                                        <div class="col-xs-4">
                                            <b>LING</b>
                                            <input type="text" name="txtLing" id="txtLing" class="form-control media" placeholder="" required>
                                            </div>
                                            <div class="col-xs-4">
                                            <b>RED</b>
                                            <input type="text" name="txtRed" id="txtRed" class="form-control media" placeholder="" required>
                                            </div>
                                            <div class="col-xs-4"></div>
                                        </div>

JQUERY:

$('.media').change(function(){

            var MAT = Number(document.getElementById("txtMat"));
            var CNAT = Number(document.getElementById("txtCNat"));
            var LING = Number(document.getElementById("txtLing"));
            var RED = Number(document.getElementById("txtRed"));

            var valorMAT = toNumber(MAT.value);
            var valorCNAT = toNumber(CNAT.value);
            var valorLING = toNumber(LING.value);
            var valorRED = toNumber(RED.value);

            MEDIA.textContent = ((valorMAT*45)+(valorCNAT*45)+(valorLING*5)+(valorRED*5))/100;


        });

Follow the layou image

    
asked by anonymous 16.12.2015 / 16:27

3 answers

2

Good afternoon,

First of all, you left the binded event in a control that is disabled, depending on whether you take the controls you play in a variable, then you create other variables to receive the value, it's not really working.

I made an example with the media being generated by a button, so we can start the process that calculates.

$('#btnAcao').on('click',function(){
        //Guarda os valores dos controles em variaveis
        var MAT = parseFloat($("#txtMat").val());
        var CNAT = parseFloat($("#txtCNat").val());
        var LING = parseFloat($("#txtLing").val());
        var RED = parseFloat($("#txtRed").val());

        //Calcula os valores
        var media = ((MAT*45)+(CNAT*45)+(LING*5)+(RED*5))/100;

        //Atribui valor no campo media
        $('#txtMedia').val(media);

    });

I gave a parseFLoat because I do not know what kind of data you're going to work on.

See an example here at jsFiddler

    
16.12.2015 / 16:53
2

You can use filter() to check for inputs empty at each change event, and only when the number of inputs is zero is the calculation performed:

var temInputVazio = $('input').filter(function(){
  return this.value == '';
}).length;

if(!temInputVazio){
  // Tira a média.
}

Example:

$(function() {

  // Função de média somente para exibição.
  var media = function(sel) {
    var soma = 0;
    $(sel).each(function() {
      soma += Number($(this).val());
    });
    return soma / $(sel).length;
  }

  
  $('input').on('change', function() {

    // Pega o número de inputs vazios.
    var temInputVazio = $('input').filter(function() {
      return this.value == '';
    }).length;

    // Se o 'length' for zero, todos foram preenchidos, então o cálculo é feito:
    if (!temInputVazio)
      $('p').text('A média é: ' + media($('input')));
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type='text' placeholder='MAT' />
<input type='text' placeholder='C NAT' />
<input type='text' placeholder='LING' />
<input type='text' placeholder='RED' />

<p></p>
    
16.12.2015 / 17:12
1

Using the same logic shown in your code, one solution is to check if any input is empty and exit the function using the return. See this example.

$('input').on('change', function() {
  var $txtValor1 = $("#txtValor1");
  var $txtValor2 = $("#txtValor2");
  var $txtValor3 = $("#txtValor3");
  var $txtValor4 = $("#txtValor4");
  var $txtMedia = $("#txtMedia");

  if ($txtValor1.val() == '')
    return limparMedia();
  if ($txtValor2.val() == '')
    return limparMedia();
  if ($txtValor3.val() == '')
    return limparMedia();
  if ($txtValor4.val() == '')
    return limparMedia();

  var valor1 = parseFloat($txtValor1.val());
  var valor2 = parseFloat($txtValor2.val());
  var valor3 = parseFloat($txtValor3.val());
  var valor4 = parseFloat($txtValor4.val());

  var media = (valor1 + valor2 + valor3 + valor4) / 4;

  $txtMedia.val(media)

});

function limparMedia() {
  var $txtMedia = $("#txtMedia");
  $txtMedia.val('');
  return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Valor1:<inputtype="text" id="txtValor1" />
<br />Valor 2:
<input type="text" id="txtValor2" />
<br />Valor 3:
<input type="text" id="txtValor3" />
<br />Valor 4:
<input type="text" id="txtValor4" />
<br />Média:
<input type="text" id="txtMedia" />

But I think it's still better to follow the @RBoschini tip by creating a button to trigger the event.

    
16.12.2015 / 17:12