Questions and discussion about developing processes and programming in PHP, JavaScript, web services & REST API.

Moderator: amosbatto

Forum rules: Please search to see if a question has already asked before creating a new topic. Please don't post the same question in multiple forums.
User avatar
By avanzyl
#825946
Hi,

I would like to sum the keys of a checkgroup using javascript. As an example, lets say I have:

var Score = []

I would like to get the key of all the values in the $("#checkgroup") that are checked. i.e. If I have a checkgroup with three options, and if the keys for those options are 1,2,3 respectively, and all 3 are checked, I would like to have var Score = 6.

Any help would be great.
User avatar
By amosbatto
#825960
Try this:
Code: Select all
var score = $("#myCheckgroup").getValue().reduce(function(total, num) {return parseInt(total) + parseInt(num);}); 
User avatar
By avanzyl
#825977
Hi Amos,

I have tried to apply the code and get the following:

VM542:12 Uncaught TypeError: Reduce of empty array with no initial value
at Array.reduce (<anonymous>)
at eval (eval at <anonymous> (VM467 jquery-1.11.js:2), <anonymous>:12:35)
at eval (<anonymous>)
at VM467 jquery-1.11.js:2
at Function.globalEval (VM467 jquery-1.11.js:2)
at m.fn.init.domManip (VM467 jquery-1.11.js:3)
at m.fn.init.append (VM467 jquery-1.11.js:3)
at Script.render (VM475 PMDynaform.js:4954)
at Project.checkScript (VM475 PMDynaform.js:2547)
at Project.loadProject (VM475 PMDynaform.js:2590)

Dont understand why though.
User avatar
By amosbatto
#825986
Either the keys of your options are not numbers or you have no selected checkboxes in the checkgroup and reduce() doesn't work on an empty array.

Try it this way:
Code: Select all
var aScores = $("#selectScores").getValue();
var score = aScores.length == 0 ? 0 : aScores.reduce(function(total, num) {
      return (isNaN(parseInt(total)) ? 0 : parseInt(total)) + (isNaN(parseInt(num)) ? 0 : parseInt(num));
});
(1.76 KiB) Downloaded 1 time
User avatar
By avanzyl
#825995
Thanks Amos,

Just on your initial comment.

This is the first time the checkgroup will be displayed to the user so there wont be any selections made. I need the score to be tallied up at the end of the form so the they could as an example be scored on what they selected in the checkgroup.

Hi Support, I think this is good. I too have fixe[…]

Hi, I'm facing the same error and when I run : […]

Routing Logic

Hi All I am doing a process, where i have 3 tasks […]

Hi @amosbatto, thanks a lot. at least the message[…]