Jquery calculate average and insert the result into the average field that is disable

Asked

Viewed 650 times

1

Good afternoon,

Needed to calculate the average of the values inserted in the 4 text boxes, and only to learn the average result in the middle 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 image of the layou inserir a descrição da imagem aqui

  • Hello, what have you done so far? Put a code there that agent can help you.

3 answers

2


Good afternoon,

First, you left the event binded in a control that this disable, second you take the controls plays in variable then creates other variables to receive the value, all this is not to actually work.

I made an example with the media being generated by a button, so we have to 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 don’t know what kind of data you will work.

See here an example on jsFiddler

  • Thanks, perfect, I just made the change to the on. ('change'...

2

You can use the function filter() to check if there are inputs empty at each change event, and only when the number of inputs is zero the calculation is 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>

1

Using the same logic shown in your code, one solution is to check if any input is empty and exits the function using 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>
Valor 1:
<input type="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.

Browser other questions tagged

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