Question : Should I use a for-loop in JavaScript to assure only one checkbox is selected?

Should I use a for-loop in JavaScript to assure only one checkbox is selected?
I have a homework to do in JavaScript where the user is supposed to check only one of three checkboxes (I'm not allowed to use radio buttons). Then, there is a button that fires off an alert with the text "Your age is..." depending on which checkbox was selected.

So far, the code is right. But the last step, to make a control so that only one checkbox has been selected I don't know how to do. If the user selects more than one checkbox, an alert should be fired off with the text "You are only allowed to check one checkbox."

Can I solve this with a for-loop? How? Should I begin something like this?:

function checkbox();
{
checkcount=0
for (i=0;

Answer : Should I use a for-loop in JavaScript to assure only one checkbox is selected?


function checkbox() { // no semicolon here
 var checkCount=0;
 var alder = document.nameOfForm.alder;
 for (var i=0; i<alder.length;i++) {
   if (alder[i].checked) checkCount+=1; // add one
 }
 if (checkCount != 1) {
   alert('Checka 1 och bare 1');
  return false;
 }
 return true;
}


However depending on where you call this, you might want to UNCHECK the one you checked too many
Random Solutions  
 
programming4us programming4us