Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

checkbox strategy 1

Status
Not open for further replies.

tfreeman2004

Technical User
Mar 15, 2004
14
US
Hi everybody, I have several groups of checkboxes with each group containing 3-14 check boxes, now I need to go through and find whether more than 3 boxes are checked in each group, the way I have this written I dont believe is the best way, I have given each box within its "group" a special name like in group one the boxes are labeled grpone1,grpone2...ect, I thought I would go through and check each box by name like
if (document.form1.grpone1==checked) ect..
all the while adding to a total for that group, is there an easier way, a way I could name all the boxes in the first group "grpone" and cycle through them to check for how many are checked or does each box need its own name. Im just learning javascript, I bought o'reilly's pocket ref yesterday and its great but I still need guidance as to strategy and I know some of you trench hardened vets can help me by suggesting a better approach, thanks in advance.
 
Hello TFreeman,
Checkboxes in each group are named the same. Also, the grouping is an array so the positions begin at zero.

Here is one way to count the checkboxes.

Code:
<HTML>
<HEAD>
<HTML>
<HEAD>
<TITLE>Test</TITLE>
<SCRIPT LANGUAGE=JavaScript>
function checkAll() {
var theCount=0;
   numCk = myForm.theCheck.length;
   for (i = 0; i < numCk; i++) {
    if(myForm.theCheck[i].checked ==true){
	 theCount++;
	}
   }
   if(theCount>=3){
//do something
   }
   else{
// do somthing else
   }
}
</SCRIPT>

<BODY>
<FORM NAME=myForm>
<INPUT TYPE=CHECKBOX NAME=theCheck onClick="checkAll()">text1<BR>
<INPUT TYPE=CHECKBOX NAME=theCheck onClick="checkAll()">text2<BR>
<INPUT TYPE=CHECKBOX NAME=theCheck onClick="checkAll()">text3<BR>
<INPUT TYPE=CHECKBOX NAME=theCheck onClick="checkAll()">text4<BR>
</FORM>
</BODY>
</HTML>
 
Thanks that works great, I would like to post this somewhere when its done so it can be critiqued by you guys because Im sure my code is laughable but it does work at this point thanks alot!
 
Ok heres what I came up with, I know its not effecient but thats the kind of stuff I hope to learn, you can look at just the java at,


or see the finished product at,


I welcome any suggestions, especially any that would keep me from having to write basicly the same function over and over like in the sleep quiz, Im still having a hard time totally understanding functions so any shorthand or advice. is appreciated.
 
I made an attempt to make a function that covered a little more ground but it doesnt work, and I dont know how to debug it , if anyone would look at


and just tell me if Im way off or kinda close or what, I see an error flash down there but it happens so quick I cant tell whats going on. just for the sake of people who dont like links I will paste most of it here
Code:
<script language="javascript">
var diagnosis,a,b,c,d,e,build=new String();
function findGroup(){
         if(group==insomChk){build="a"}
	      else if(group==apnChk){build="b"}
	      else if(group==narcChk){build="c"}
	      else if(group==gastChk){build="d"}
	      else if(group==myNocChk){build="e"}
		  }
function buildIt(){
     if(build=="a"){a = "<li>You show signs of insomnia, a persistent inability to fall asleep or stay asleep</li><br>";}
	 else if(build=="b"){b="<li>You show signs of sleep apnea, a life threatening disorder that causes you to stop breathing repeatedly during sleep often hundreds of times per night.</li><br>";}
	 else if(build=="c"){c="<li>You show signs of narcolepsy, a life long disorder characterized by uncontrollable sleep attacks during the day.</li><br>";}
	 else if(build=="d"){d="<li>You show signs of gastroesophageal reflux, a disorder cause when acid from the stomach 'backs up' into the esophagus at night.</li><br>";}
	 else if(build=="e"){e='<li>You show signs of nocturnal myoclonus or restless leg syndrome, a disorder characterized by pain or "crawling" sensations in the legs.</li><br> ';}
 }
 //my attempt a wider function
function quizScore(group){
    var total=0;
    numCk = quiz.getElementByName(group).length;
	for (i = 0; i < numCk; i++)
	  {if(quiz.getElementByName(group)[i].checked==true)
	          {total++;}
		 }
            if(total>=3){
  		findGroup();
	        buildIt();
	}	
}
function doAll(){
	quizScore(insomChk,apnChk,narcChk,gastChk,ChkmyNoc);
	diagnosis=a+b+c+d+e;
	if (diagnosis.length<1){diagnosis="<center><h3>Congratulations, you show no signs of a sleep disorder.</h3></center><br>";}
	writeConsole(diagnosis);
	}
</script>
 
hi tfreeman2004,

you can consolidate all your script into just this:

Code:
function getNumChecked(o) {
	if (!o.length) {
		return ((o.checked) ? 1 : 0);
	}
	else {
		var c = 0;
		for (var x = 0; x < o.length; x++) {
			if (o[x].checked) c++;
		}
		return c;
	}
}

function doAll(f) {
  var diagnosis = "";
  
  if (getNumChecked(f.insomChk) > 2) 
    diagnosis += "<li>You show signs of insomnia,"
      + " a persistent inability to fall asleep"
      + " or stay asleep</li><br>";
  if (getNumChecked(f.apnChk) > 2) 
    diagnosis += "<li>You show signs of sleep apnea,"
      + " a life threatening disorder that causes"
      + " you to stop breathing repeatedly during"
      + " sleep often hundreds of times per night."
      + "</li><br>";
  if (getNumChecked(f.narcChk) > 2) 
    diagnosis += "<li>You show signs of narcolepsy,"
      + " a life long disorder characterized by"
      + " uncontrollable sleep attacks during the day."
      + "</li><br>";
  if (getNumChecked(f.gastChk) > 2) 
    diagnosis += "<li>You show signs of gastroesophageal"
      + " reflux, a disorder cause when acid from the"
      + " stomach 'backs up' into the esophagus at night."
      + "</li><br>";
  if (getNumChecked(f.nocMyChk) > 2) 
    diagnosis += "<li>You show signs of nocturnal"
      + " myoclonus or restless leg syndrome, a disorder"
      + " characterized by pain or 'crawling' sensations"
      + " in the legs.</li><br>";
  
  if (diagnosis.length == 0)
    diagnosis = "<center><h3>Congratulations, you show"
      + " no signs of a sleep disorder.</h3></center><br>";
    
  writeConsole(diagnosis);
}

function writeConsole(content) {
 top.consoleRef=window.open('','testResult',
  'width=570,height=325'
   +',menubar=0'
   +',toolbar=0'
   +',status=0'
   +',scrollbars=0'
   +',resizable=1')
 top.consoleRef.document.open();
 top.consoleRef.document.writeln(
  '<html><head><title>Your Results</title></head>'
   +'<body bgcolor=white onLoad="self.focus()">'
   +'<center><h2>Your Results</h2></center>'
   +'<hr><br><ul>'
   +content
   +'</ul></body></html>' )
 top.consoleRef.document.close();
}

NOTE however that you need to remove all your separate forms, and instead wrap all form elements in just one form.

you also need to change your submit button like so to accommodate the above changes:
<input type="submit" value="Get Results" onClick="doAll(this.form);" name="submit">


hope this helps

=========================================================
-jeff
try { succeed(); } catch(E) { tryAgain(); }
 
Thanks jemminger, I can follow almost all of that with no problem I should be able to continue studying it to get a better idea of how I should structure my stuff, however your code for getNumChecked is hard for me to follow but I really want to understand whats its doing, I looked in my pocket ref for ! and I still dont know what a logical complement is, at any rate is there anyone here willing to walk me through the code below?
Code:
function getNumChecked(o) {
    if (!o.length) {
        return ((o.checked) ? 1 : 0);
    }
    else {
        var c = 0;
        for (var x = 0; x < o.length; x++) {
            if (o[x].checked) c++;
        }
        return c;
    }
}
 
!" means "not", so

if (!o.length) {

means "if the o.length property does not exist"


this:
(o.checked) ? 1 : 0

is a ternary operator, which has the form
a ? b : c;

which is equivalent to "if a is true then b else c"


=========================================================
-jeff
try { succeed(); } catch(E) { tryAgain(); }
 
man thats great! But I have a very basic question now, where are those values being returned to?

return ((o.checked) ? 1 : 0); and return c;

Im trying to invision this thing evaluating and passing along its solutuions to the next chunk of code but Im unsure about the proper use of return(). I know this is basic but Im just learning and I appreciate your help. Im also a little confused about for loops does the initialization part of the loop get ommited after the first time? I guess it does since x cant continuously be 0 or it would never stop but Im not 100% sure or what is acually happening.
 
they are being returned to whatever called the function, e.g.
Code:
function difference(a,b) {
  return a - b;
}

var c = difference(22,10);
var d = difference(6,2);

the function difference() returns its value to the variables "c" and "d"

=========================================================
-jeff
try { succeed(); } catch(E) { tryAgain(); }
 
So can I assume that in this line the value is being returned to the if statment.
Code:
if (!o.length) {
        return ((o.checked) ? 1 : 0);}
and here being returned to the main function
Code:
 return c;

Youve already helped me to clear up several things , thanks alot!
 
>> "So can I assume that in this line the value is being returned to the if statment."
no - return always exits the function entirely with the assigned value.



=========================================================
-jeff
try { succeed(); } catch(E) { tryAgain(); }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top