1

Here's the deal. The task is to write a function which should be able determine the number of checkboxes checked for each question and prompt a user if more than 3 answers were selected. I have a total of 8 questions and each question has 4 to 8 answers, in the checkbox format. This is what I came up with:

function countChecks(){
   var m = 0;
   var n = 0;
 chk = document.getElementsByName("DSelectionID");

  for(var i=0; i<myitems.length i=""></myitems.length>
   var value = myItems[i];

  for(n = 0; n < value.length; n++) {
 if(value[n].checked)  {
  m++;
 }
 }
 return m;
 }

the above function works fine for one question and returns 'm' to the main function, which handles it this way:

var check = countchecks();

if (check > 3)
 alert ("more than 3 checkboxes were selected");
   else { 
 //do the thing 
}  

to traverse all the 8 questions this is what I came up with:

 function countChecks(){

   var m = 0;
   var n = 0;

//this captures id's for the right questions

 chk = document.getElementsByName("DSelectionID");
 chk2 = document.getElementsByName("DSelectionID2");
 chk3 = document.getElementsByName("DSelectionID3");
 chk4 = document.getElementsByName("DSelectionID4");
 chk5 = document.getElementsByName("DSelectionID5");
 chk6 = document.getElementsByName("DSelectionID6");
 chk8 = document.getElementsByName("DSelectionID8");
 chk9 = document.getElementsByName("DSelectionID9");

  var myItems = new Array();

  myItems[0]= chk;
  myItems[1]= chk2;
  myItems[2]= chk3;
  myItems[3]= chk4;
  myItems[4]= chk5;
  myItems[5]= chk6;
  myItems[6]= chk8;
  myItems[7]= chk9;

//loops through all the questions for(var i=0; i var value = myItems[i];

//loops through the checkboxes for each question

 for(n = 0; n < value.length; n++)
  {
  if( value[n].checked)
  {
      m++;
     if (m > 3) {
    return false; 
   }
  }
 }
   }
}

and the main body handles it like this:

var check = countChecks() 
if (check == false)
alert ("more than 3 checkboxes were selected");
   else {
//do the thing
  }

It is something very simple I'm missing in the countChecks() function Any ideas?

2 Answers 2

2

Using jquery would make this pretty trivial

if ($('#yourform input[type=checkbox]:checked').length() > 3) {
   alert('More than 3 checked');
}
Sign up to request clarification or add additional context in comments.

Comments

0

chk = document.getElementsByName("DSelectionID"); does not grab the ID, it grabs a reference to the element in the DOM.

To get the ID you need to use:

chk = document.getElementsByName("DSelectionID").getAttribute("id")

1 Comment

It returns a DOM NodeList, which is basically an array of matching elements, actually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.