Sum and control total in a grid question

Compatibility:IdSurvey 5IdSurvey 6

The script sums all positive numerical values in an open end grid column showing the total at the end of the grid. It also runs a control on the total, preventing the questionnaire from proceeding if the number is different from the value set in the script. The script does not check for negative numbers, which are considered as having a value of 0 in the final sum.

Please Note: the page on which the script is applied, must contain a single matrix question. The script is not compatible with 3D matrixes and simple matrixes with more than one column when filling a CAWI survey via smartphone.

Instructions

Paste the script in the Client script box. You can find this in the gearwheel button of the page containing the grid.

You can also edit the error message and the total value (see parts marked in red in the script). The total sum will be displayed under the grid, with the label “Amount” (this can be changed by changing the string marked in green in the script below).

<clientscript>
 <script>
 /* This script check the sum of all numbers typed on text fields on a page and show an alert if the amount is not equal to the set amount.
That amount is shown below the text column.*/
 var errorMessage = "Check your data. Total has to be 100." // you can change the alert text
 var amount = 100 // you can modify the number to check
 /* don't modify the script below */
 var somma = 0;
 $(".grid-question-table.table").find("tfoot th:last").html("amount: <span id='totSomma'> 0 </span>").show();
 function sommaTutto(){
 somma= 0;
 $(":text:visible, input[type='number']:visible").each(function(e){
 var sp = 0;
 sp= parseInt($(this).val());
 if(!isNaN(sp) && sp >= 0)
 somma += sp;
 $("#totSomma").html(somma);
 });
 }
 $("input[type='number'], :text").on("keyup change", function(){
 sommaTutto();
 });
 $("input[type='number']:first:visible, :text:first:visible").trigger("change");
 $("#nextPage").off("click").on("click",function(e){
 sommaTutto();
 if(somma==amount){
 nextPageClickHandler.call(this, e);
 }else{
 e.preventDefault();
 e.stopPropagation();
 alert(errorMessage);
 return false;
 }
 });
 </script>
 <style>
 .grid-question-table tfoot{
 display:table-footer-group !important;
 }
 </style>
 </clientscript>

Sum_Control_Grid

Leave A Comment?