Ad

How To Stop Empty Input Fields From Affecting Calculations In A Form

- 1 answer

I have a form which calculates the sum and average of a set of user entered values. Users can dynamically add input fields so that they may find the sum and average of as many data values as they wish. I am trying to proof it such that if they happen to add a field but leave it blank, that input field will be ignored in the calculations. When left blank at present, the form returns 'NaN,NaN'. I have tried this

$(':input[value=""]').attr('name', ''); 

based on a quick search, but it did not have the intended effect (the form still returns 'NaN,NaN'.

The calculations are performed when the user clicks a button using the following jQuery

$(".calc").click(function() {
   $("input[type=text]").each(function() {
    arr.push($(this).val());
    sum += parseInt($(this).val());       
  });

  var n = arr.length;
  var AVG = (sum / n);
  alert(sum + "," + AVG);
  arr = [];
  sum = 0;
});

Any suggestions?

Ad

Answer

Try like this below. I have added trim as well to filter the empty spaces.

$(".calc").click(function() {
   $("input[type=text]").each(function() {
    arr.push($(this).val().trim() || 0);
    sum += parseInt($(this).val().trim() || 0);       
  });

  var n = arr.sort().filter(function(i){return i}).length;
  var AVG = (sum / n);
  alert(sum + "," + AVG);
  arr = [];
  sum = 0;
});
Ad
source: stackoverflow.com
Ad