Reputation: 3190
I am developing a patient satisfaction questionnaire. I have a form validation script that should check whether one or more items in the A sub-section has been given a score, if on the A main question certain radios are checked. It looks like this at the moment:
function countRadiosChecked(chdRds) {
var cnt = -1;
for (i=chdRds.length-1; i>-1; i--) {
if (chdRds[i].checked)
{cnt=i; i=-1;}
}
if (cnt > -1) return chdRds[cnt].value;
else return null; /* = the number, not the value of the radio buttons */
}
function checkASection() {
if ((upssForm.A[0].checked == true) || (upssForm.A[1].checked == true) || (upssForm.A[2].checked == true) || (upssForm.A[4].checked == true)) {
var itemsANamesArray = ['A1a','A1b','A1c','A1d','A1e','A1f','A1g','A2a','A2b','A2c','A2d','A2e','A2f','A2g','A2h','A2i','A2j','A2k','A2l','A2m','A2n','A2o','A2p','A2q','A2r'];
var thatAName = null;
var itemsANamesArrayCount = itemsANamesArray.length;
for (i=0; i<itemsANamesArrayCount; i++) {
thatAName = itemsANamesArray[i];
var thatANameGroup = upssForm.elements[thatAName];
var nrOfRadiosChecked = countRadiosChecked(thatANameGroup);
if (nrOfRadiosChecked == null)
{
alert('No item in the A sub-section has been given a score');
return;
}
return;
}
}
}
But the script already gives an alert if on the first item no score has been given, while it should loop through the whole array before alerting, if necessary. How do I that?
Upvotes: 0
Views: 78
Reputation: 757
Try this
function countRadiosChecked(chdRds) {
var cnt = 0;
for (var i=chdRds.length-1; i>-1; i--) {
if (chdRds[i].checked){
cnt = 1;
break;
}
}
return cnt;
}
function checkASection() {
if ((upssForm.A[0].checked == true) || (upssForm.A[1].checked == true) || (upssForm.A[2].checked == true) || (upssForm.A[4].checked == true)) {
var itemsANamesArray = ['A1a','A1b','A1c','A1d','A1e','A1f','A1g','A2a','A2b','A2c','A2d','A2e','A2f','A2g','A2h','A2i','A2j','A2k','A2l','A2m','A2n','A2o','A2p','A2q','A2r'];
var thatAName = null;
var itemsANamesArrayCount = itemsANamesArray.length;
var nrOfRadiosChecked =0;
for (var i=0; i<itemsANamesArrayCount; i++) {
thatAName = itemsANamesArray[i];
var thatANameGroup = upssForm.elements[thatAName];
nrOfRadiosChecked = nrOfRadiosChecked + countRadiosChecked(thatANameGroup);
}
if (nrOfRadiosChecked == 0){
alert('No item in the A sub-section has been given a score');
return;
}
return;
}
}
Upvotes: 1