freshest
freshest

Reputation: 6241

jQuery - Perform a Calculation

I have the following 3 input fields in a form:

<input id="a" name="a" type="text" />
<input id="b" name="b" type="text" />
<input id="c" name="c" type="text" />

and the following paragraph:

<p id="grand_total"></p>

I want to multiply the three text inputs together and fill in the grand_total with the result.

I only want the result to appear when we have filled in all three text inputs with integers between 0 and 1000.

Also if any of the text field values are changed to another valid integer then I want the grand_total to be re-calculated. Any help would be much appreciated, thanks.

Upvotes: 1

Views: 1493

Answers (6)

brendan
brendan

Reputation: 29976

This code will make sure each value is a number, if it is not it will default to 0 for that value:

$("#a").change(Calc());
$("#b").change(Calc());
$("#c").change(Calc());    

function Calc() {
var vals = [];
vals.push($("#a").val());
vals.push($("#b").val());
vals.push($("#c").val());

var a = isNaN(parseInt(vals[0])) ? 0 : parseInt(vals[0]);
var b = isNaN(parseInt(vals[1])) ? 0 : parseInt(vals[1]);
var c = isNaN(vals[2]) ? 0 : parseInt(vals[3]);

if(a>-1 && a<1001 && b>-1 && b<1001 && c>-1 && c<1001)
  $("#grand_total").html(a * b * c);
}

Upvotes: 0

freshest
freshest

Reputation: 6241

@brendan put me in the right direction, thanks. The code below works:

$(document).ready(function () {

  $('#a, #b, #c').change(function () {
    var a = parseInt( $("#a").val(), 10 );
    var b = parseInt( $("#b").val(), 10 );
    var c = parseInt( $("#c").val(), 10 );
    a = isNaN(a) ? 0 : a;
    b = isNaN(b) ? 0 : b;
    c = isNaN(b) ? 0 : c;
    ( a > 0 && a < 1000 && b > 0 && b < 1000 && c > 0 && c < 1000 ) ? $('#grand_total').html( a * b * c ) : $('#grand_total').html(0);
  });

});

Upvotes: 1

Šime Vidas
Šime Vidas

Reputation: 185873

var $inputs = $("#a, #b, #c");
var $result = $("#grand_total");

$inputs.change(function() {    
    var sum = 0;
    var valid = true;

    $inputs.each(function() {
        var n = parseInt($(this).val(), 10);

        if ( isNaN(n) || n < 0 || n > 1000 ) { 
            return valid = false;
        } else {
            sum *= n;
        }
    });

    valid ? $result.text(sum).show() : $result.hide();
});

Upvotes: 0

Ionuț Staicu
Ionuț Staicu

Reputation: 22156

Optimized version:

var a = parseInt($('#a').val(), 10) || 0,
    b = parseInt($('#b').val(), 10) || 0,
    c = parseInt($('#c').val(), 10) || 0;
    $('#grand_total').html(a+b+c);

Just make sure you use 10 as argument in parseInt() to avoid unpleasant surprises ;)

Upvotes: 0

RoToRa
RoToRa

Reputation: 38390

function calcSum(inputs) {
  var sum = 0;
  var error = false;

  inputs.each(function () {
    var value = +$(this).val() || 0;
    if (value < 0 || value > 1000) {
      error = true;
      return false; //Stops "each" loop
    }
    sum += value;
  });

  if (error) {
    ("#grand_total").text("Invalid number(s)");
  } else {
    $("#grand_total").text(sum);
  }
}

$("#a,#b,#c").change(function() { calcSum($("#a,#b,#c")); });

Upvotes: 0

Bojangles
Bojangles

Reputation: 101473

Try this:

if($("#a").val().length && $("#b").val().length && $("#c").val().length)
{
    $("#grand_total").html((parseInt($("#a").val()) + parseInt($("#b").val()) + parseInt($("#c").val())));
}

What this does is check whether all the inputs have values in them. If they all contain something, the inner statement parses all the values as ints and plugs the output into grand_total

If you want to parse as floats instead of ints, simply replace parseInt() with parseFloat()

Cheers,

James

Upvotes: 0

Related Questions