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

Moderators: ArturoRobles, ArturoRobles

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

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 avanzyl
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
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 25 times
User avatar
By avanzyl
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.
CRUD and Process

Liliana i want to hear your answer if i say "[…]

Enabling SQL Server in Windows

I’m excited to uncover this page. I need to […]

Hi, Please use query like this: SELECT Forneced.[…]

Casos estão carregando em branco

Boa tarde! Prezados, estou com problemas em algun[…]