...

View Full Version : Counting grand totals of check boxes



htims
05-28-2012, 12:10 PM
Hi there,
I'm fairly new to javascript and have to amend some code to count the value of check boxes. If the overall score is less than 4, I need to force the user to enter a comment into the comment box.
Here is a snippet of the existing code:
[CODE] <script language="javascript">

function validate() {
if (validateRatings() && validateLowScore() && validateComments()) {
return true;
}else {
return false;
}
}

function validateLowScore() {
var c = document.feedback.elements['comments'];
var msg, question
msg = '';

for(i=1;i<6;i++) { //start of outer for loop
question = eval("document.feedback.q" + i + "answer");

} // end of outer for loop
if (c.value == '' && document.feedback.q5answer(0).status == true) msg += 'You gave a low scoring for question 5. Please submit a comment ' + '\n';
if(msg == '') { //start of if
return true;
}else { // end of if and start of else
alert(msg);
return false;
} //end of else

} // end of function


function validateComments() {
var c = document.feedback.elements['comments'];
if (c.value == '') {
return confirm ('Click OK to leave comments blank. \nClick CANCEL to fill out the comments field.');
}
return true;
}

function validateRatings() {
var msg, question
msg = '';

for(i=1;i<6;i++) {
question = eval("document.feedback.q" + i + "answer");
radio: // label loop for exit
for(j=0;j<question.length;j++) {
// If answer given exit radio loop to move to the next question
if (question[j].checked) break radio;
// If no answer given by last value set the error msg for question
if (j == question.length - 1) msg += 'Please answer question ' + i + '\n';
}
}

if(msg == '') {
return true;
}else {
alert(msg);
return false;
}
}

NB There are 5 questions on the form with a possibility of scoring between 1 - 7 for each (there are 35 check boxes).

TIA

Old Pedant
05-29-2012, 04:50 AM
Please show your HTML <form> and fields.

There is no reason to use eval( ) for any of this.

And it's a bad idea to use alert( ) for messages, as some modern browsers allow the user to tell them to stop showing alerts.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum