Jquery simple sum

I have an unknown number of input fields that have a class of "add", I just want to summarize them using jquery, I don’t know where I am mistaken.

<input name="add" class="add" type="text"> <input name="add" class="add" type="text"> <input name="add" class="add" type="text"> <input name="add" class="add" type="text"> <input type="button" value="" onClick="add()" /> 

`

 function add(){ val = 0; $(".add").each(function() { str = (parseInt(this.value)) sum=str+str }); alert (sum) } 

`

+4
source share
3 answers

You never add material to sum :

 function add() { var sum = 0; $(".add").each(function() { sum += +this.value; }); return sum; // an add function shouldn't really "alert" } 

If the goal is to support only integers, use parseInt(this.value, 10) [note the radix parameter] instead of +this.value :

 function add() { var sum = 0; $(".add").each(function() { var str = this.value.trim(); // .trim() may need a shim if (str) { // don't send blank values to `parseInt` sum += parseInt(str, 10); } }); return sum; } 

See http://jsfiddle.net/alnitak/eHsJP/

+5
source
 function add(){ var sum = 0; $(".add").each(function() { var val = parseInt($(this).val(), 10) sum += (!isNaN(val) ? val : 0); }); alert(sum); } 

Edit: Keen eyes, got brackets ... =) And space.

+4
source

If you don't need to support IE8, you can use the native Javascript method Array.prototype.reduce() . First you need to convert the jQuery object to an array:

 function add() { return $('.add').toArray().reduce(function(sum,element) { return sum + Number(element.value); }, 0); } 

Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

0
source

Source: https://habr.com/ru/post/1412141/


All Articles