disable checkboxes by using getElementByName
Hello everyone:
I am doing an exercise in which checkboxes in a group will be enabled / disabled based on radio button selection.
I did some online research found this example (http://www.dynamicdrive.com/forums/showthread.php?t=3655). The example showed that using a for loop to loop thought check box group and used DOM disabled property to disable each checkbox in turn.
I have two question regarding the sample code
a) I don't understand how name="cat[]" works.
b) notation in the for loop
for(i = 1; document.getElementById("catbox" + i) !== null; i++)
"catbox" is not match with id value "cat1"
b1 my understanding is that for loop will go through each checkbox starts from first one until it reached
last check box in the group. Am I right about this for loop logic?
b2 why it uses strict not equal here?
I modified my code and test it in browser it doesn't disable the checkboxes. Could someone check my code and tell me what I did wrong? Thanks for you help!
HTML Code:
<form name="account_form" id="account_form" action="" method="post">
<input type="radio" name="class" id="under_graduate" value="under_graduate"
onclick="checkAccountStatus()" />Undergraduate student
<input type="radio" name="class" id="graduate" value="graduate"
onclick="checkAccountStatus()" />Graduate student<br /><br />
<input type="checkbox" name="grad_account[]" id="grad_account1" value="dsl_account" />DSL Account<br />
<input type="checkbox" name="grad_account[]" id="grad_account2" value="unix_account" />Unix Account<br />
<input type="checkbox" name="grad_account[]" id="grad_account3" value="web_host" />Web Hosting<br />
<input type="checkbox" name="grad_account[]" id="grad_account4" value="list_server" />List Server
<p>
<input type="submit" name="submit" value="submit" />
<input type="reset" name="reset" value="reset" />
</p>
</form>
JavaScript Code to disable checkboxes:
function checkAccountStatus()
{
with(document.account_form)
{
function disableGraduateAccount()
{
for(var k = 1; document.getElementById("grad_account" + i) !== null; k++)
{
document.getElementById("grad_account" + k).disabled = true;
}
}
//loop through radio button group to check which button being checked
for(var i = 0; i < class.length; i++)
{
if(class[i].checked && class[i].value == 'under_graduate')
{
disableGraduateAccount();
}
}
return true;
}//end of with statement
}
sjcoder07
5-20-07
[3000 byte] By [
sjcoder07] at [2007-11-20 8:02:10]

# 1 Re: disable checkboxes by using getElementByName
I'm seeing multiple problems.
1. You are using onclick and not onchange. What if the user is proficient in keyboard shortcuts? Your event will never fire.
2. You have class.length called in a for loop. You are attempting to get the name but that isn't proper.
3. Your function within a function is very confusing and does extra work that is unnecessary.
4. Try...
<script type="text/javascript">
function checkAccountStatus(event){
var chkbox;
if(document.all){chkbox = window.event.srcElement;}
else{chkbox = event.target;}
var theInputs = document.getElementsByTagName('input');
for(i=0;i<theInputs.length;i++){
if(theInputs[i].name.substr(0, 12) == 'grad_account'){
if(chkbox.checked && chkbox.value == 'under_graduate'){theInputs[i].disabled = true;}
else{theInputs[i].disabled = false;}
}
}
}
</script>
<form name="account_form" id="account_form" action="" method="post">
<input type="radio" name="class" id="under_graduate" value="under_graduate" onclick="checkAccountStatus(event)" />Undergraduate student
<input type="radio" name="class" id="graduate" value="graduate" onclick="checkAccountStatus(event)" checked />Graduate student<br /><br />
<input type="checkbox" name="grad_account[]" id="grad_account1" value="dsl_account" />DSL Account<br />
<input type="checkbox" name="grad_account[]" id="grad_account2" value="unix_account" />Unix Account<br />
<input type="checkbox" name="grad_account[]" id="grad_account3" value="web_host" />Web Hosting<br />
<input type="checkbox" name="grad_account[]" id="grad_account4" value="list_server" />List Server
<p>
<input type="submit" name="submit" value="submit" />
<input type="reset" name="reset" value="reset" />
</p>
</form>
# 2 Re: disable checkboxes by using getElementByName
Hello Peej:
Thanks for replying my message. Your code is more efficent compare to mine.
I tried antother approach to enable / disable checkboxes without array notation. It worked.
JavaScript code:
function disableGraduateAccount(frm)
{
for(var k = 0; k < frm.grad_account.length; k++)
{
frm.grad_account[k].disabled = true;
}
}
function checkAccountStatus(frm)
{
with(frm)
{
alert(class.length);
var e, i = 0;
for(var i = 0; i <class.length; i++)
{
if(class[i].checked && class[i].value == 'under_graduate')
{
disableGraduateAccount(frm)
}
else if(class[i].checked && class[i].value == 'graduate')
{
enableGraduateAccount(frm);
}
}
}//end of with statement
}
I will posted my 2nd attempt which used getElementByName to access
checkboxes using array notation.
sjcoder07
# 3 Re: disable checkboxes by using getElementByName
Hello everyone:
I tried disable chebox in array form by using getElementByName property. But my attempt failed.
my previous post (http://www.dev-archive.com/forum/showthread.php?t=424050) (1st attempt) doesn't work out either.
I referenced this forum discussion (http://www.webdeveloper.com/forum/showthread.php?t=80621) and modified my code.
Please advise me how to make this code working
HTML code segment:
a) I don't understand how getElementByName("grad_account[]")[i++]) works.
seems to me that grad_account[] is an array contain all the checkboxes' namethen when i got incremented, it will lead to grad_account[i] to access each checkbox.
why grad_account need to be quoted and followed by array index?
<form name="account_form" id="account_form" action="" method="post">
<input type="radio" name="class" id="under_graduate" value="under_graduate"
onclick="return checkAccountStatus(this)" />Undergraduate student
<input type="radio" name="class" id="graduate" value="graduate"
onclick="checkAccountStatus()" />Graduate student<br /><br />
<input type="checkbox" name="grad_account[]" id="grad_account1" value="dsl_account" />DSL Account<br />
<input type="checkbox" name="grad_account[]" id="grad_account2" value="unix_account" />Unix Account<br />
<input type="checkbox" name="grad_account[]" id="grad_account3" value="web_host" />Web Hosting<br />
<input type="checkbox" name="grad_account[]" id="grad_account4" value="list_server" />List Server
<p>
<input type="submit" name="submit" value="submit" />
<input type="reset" name="reset" value="reset" />
</p>
</form>
JavaScript Code Segment:
Firefox javascript console complained that "document.getElementByName is not a function" I couldn't figure out what went wrong.
function disableGraduateAccount()
{
var e, i = 0;
while( e = document.getElementByName("grad_account[]")[i++])
{
e.disabled = true;
}
}
function checkAccountStatus(radioBtnObj)
{
with(document.account_form)
{
if(radioBtnObj.checked && radioBtnObj.value == 'under_graduate')
{
disableGraduateAccount(this.form);
}
}//end of with statement
}
sjcoder07
5-22-07
# 4 Re: disable checkboxes by using getElementByName
Can this thread just be merged into your other one? It would take less resources that way.
document.getElementByName() doesn't exist. It is document.getElementsByName(), and it returns an object of all the elements that can be accessed as an array. Here is how I would change the first function:
function disableGraduateAccount() {
for(var e,i;document.getElementByName("grad_account[]")[i];i++)
e.disabled = true;
}
if e.disabled = true; doesn't work, you may want to try:
e.setAttribute("disabled","true");
# 5 Re: disable checkboxes by using getElementByName
I tried disable chebox in array form by using getElementByName property. But my attempt failed.
If my example worked, as you said, why are you still wrestling with this?
Can this thread just be merged into your other one? It would take less resources that way.
That would probably be best. They are the same issue.
# 6 Re: disable checkboxes by using getElementByName
Hi Dr. Scrpt and Peej:
Thanks for the help!. I solved my problem. I encounter another one problem. Here I am again try to look for help.
I am doing an form validation exercise(self-designed). I used JavaScript to validate the user input. sample code (http://www.cuj06.com/js_project/multi_fieldValidation.html)
The form is designed for students to regiester accounts available at university's computing center.
I have textfields, textarea, radio buttons, checkboxes, selection list(drop-down)list.
The validation process took place when user click submit button (I used onSubmit event handler to call
form_validation function)
HTML code:
<form name="account_form" id="account_form" action="" method ="post" onSubmit="return form_validation()">
I used a for loop to go through each element on the form, inside for loop I have a switch
statement that calls validation function based on the NAME attribute of the element.
Each individual validation function will return true or false back to switch statement where a boolen varible validatedOK will store the result.
JavaScrpt code:
for(var i = 0; i<(elements.length - 2); i++)
{
switch(elements[i].name)
{
case "fname":
validatedOK= checkFirstName(first_name_field); //pass a reference to first name field to function
break;
....//other case statements
case "class":
validatedOK= checkAccountStatus(frm);
break;
case "grad_account":
//skip checkbox verification for enable/disable checkbox purpose
break;
default:
alert("no such element exist on the form");
break;
}
//after the switch statement if return value for
//validatedOk is false call a function to return false to html file
//so form won't get submitted
if (!validatedOK)
{
return false;
}
//increment the counter, when all the elements on the form
//has passed validation test, call same function
//return 'true' to html file, so form can be submitted
else
{
checked_counter++; //when checked_counter equals to elements.length - 2
//this means every field has passed validation test
if (checked_counter == elements.length - 2)
{
var status = true;
return status;
}
}
}//end of for loop
/*
function checkAccountStatus
enable/disable graduate account(checkboxes) - base on radio button selection
*/
function disableGraduateAccount(frm)
{
for(var k = 0; k < frm.grad_account.length; k++)
{
frm.grad_account[k].disabled = true;
}
}
function enableGraduateAccount(frm)
{
for(var j = 0; j < frm.grad_account.length; j++)
{
frm.grad_account[j].disabled = false;
}
}
//frm represent form object that contains the under_graduate radio button
function checkAccountStatus(frm)
{
with(document.account_form)
{
var classCtr = -1;
for(var i = 0; i < class.length; i++)
{
if(class[i].checked && class[i].value == 'under_graduate')
{
classCtr = i;
disableGraduateAccount(frm)
}
else if(class[i].checked && class[i].value == 'graduate')
{
classCtr = i;
enableGraduateAccount(frm);
}
}
if(classCtr == -1)
{
alert("you must select either Undergraduate or Graduate radio button.");
return false;
}
else
return true;
}//end of with statement
}
My problem occured when I need to enable/disable computer accounts (represented by checkboxes) for graduate students. Enable/disable action are based on radio button selection.
If user select undergraduate radio button, program should disable the computer accounts for graduate
student. If user selet graduate student button, program should enable computer accouts for graduate student.
I called validation function check_account status by using onclick event handler in radio button section
HTML code:
<input type="radio" name="class" id="under_graduate" value="under_graduate" onclick="checkAccountStatus(this.form)" />Undergraduate student
<input type="radio" name="class" id="graduate" value="graduate" onclick="checkAccountStatus(this.form)" />Graduate student<br /><br />
a) But by solving problem this way I bypassed the switch statement. My purpose is to stop form submission if there is a validation error.
Firfox javascript cosole complained after user submit form that 'frm' is not defined
case "class":
validatedOK= checkAccountStatus(frm);
break;
b)I am also confused should I return the boolean value back to switch statement.The only case to return
false is user didn't select either graduate or undergraduate radio button.
I hope I explained my problem clearly. Please check my code and give me some suggestions so that
I can used switch statement to handle enable /disable checkboxes and have boolean value reurned corretly
to onSubmit event handler.
Thanks for reading my post. I appreciate your patience and help!
P.S. I final step for this exercise is to use PHP to send out a confirmation email that contains user's a account information from the from.
sjcoder07
5-24-07
# 7 Re: disable checkboxes by using getElementByName
Firfox javascript cosole complained after user submit form that 'frm' is not defined
That is because you haven't defined it. You see, in your functions frm is a parameter you are passing to it. However, switch statements don't have parameters. So where are you declaring the variable frm in the switch statement?
# 8 Re: disable checkboxes by using getElementByName
That is because you haven't defined it. You see, in your functions frm is a parameter you are passing to it. However, switch statements don't have parameters. So where are you declaring the variable frm in the switch statement?
Hello Peej:
I figured out that I need to verify radio buttons (undergraduate and graduate students ) before form being submitted. If I verify checked property after form being submitted, I can't disable graduate students accounts(checkboxes) once user selected undergraduate account, then submit the form.
I couldn't figure out how to handle radio buttons inside switch statement inside form_validation function. Since I called checkAccountStatus(this.form) function before form being submitted.
My switch statement suppose to call validation function based on the NAME attribute of the element on the form. If all the elements passed validation test, true is returned; otherwise , false is returned.
I posted my entire code here, please give me some hints on how to deal with radio buttons selection and graduate account selection inside switch statement. Thanks!
My HTML code:
<html>
<head>
<title>form validation-name field</title>
<script src="form_validation.js" type="text/javascript"></script>
</head>
<body onload="document.account_form.fname.focus()">
<form name="account_form" id="account_form" action="" method ="post" onSubmit="return form_validation()">
First Name: <input type="text" name="fname" id="fname" value="" maxlength="20"><br /><br />
Last Name: <input type="text" name="lname" id="lname" value="" maxlength="20"><br /><br />
age: <input type="text" name="age" id="age" value="" maxlength="3"><br /><br />
<input type="radio" name="gender" id="maleR" value="male" />Male <br /><br />
<input type="radio" name="gender" id="femaleR" value="female" />Female <br /><br />
<!-- selection list -------->
<select name="departments" id="departments">
<option value="none">select your department</option>
<option value="art">Arts</option>
<option value="bio">Biology</option>
<option value="cs">Computer Science</option>
<option value="eng">English</option>
<option value="math">Mathematics</option>
<option value="geology">Geology</option>
<option value="history">History</option>
<option value="physics">Physics</option>
</select><br /><br />
Email <input type="text" name="email" id="email" size="30" maxlength="30" /><br /><br />
Phone Number <input type="text" name="phone_num" id="phone_num" size="14" maxlength="14" />
(enter a phone number like 4084445566)<br /><br />
<!--
account selection - undergraduate or graduate students
enable/disable graduate account(checkboxes) - base on radio button selection
-->
<!-- onclick="return checkAccountStatus(this.form)" -->
<input type="radio" name="class" id="under_graduate" value="under_graduate" onclick="checkAccountStatus(this.form)" />Undergraduate student
<input type="radio" name="class" id="graduate" value="graduate" onclick="checkAccountStatus(this.form)" />Graduate student<br /><br />
<p>Accounts for All Student</p>
<input type="checkbox" name="undergrad_account" id="undergrad_account1" value="dial_up" />Dial Up<br />
<input type="checkbox" name="undergrad_account" id="undergrad_account2" value="pc_lab" />Computer Lab<br />
<input type="checkbox" name="undergrad_account" id="undergrad_account3" value="music_movie" />Music/Movie Download<br /><br />
<p>Accounts for Graduate Student Only</p>
<input type="checkbox" name="grad_account" id="grad_account1" value="dsl_account" onclick="checkGraduateAccount(this.form)" />DSL Account<br />
<input type="checkbox" name="grad_account" id="grad_account2" value="unix_account" onclick="checkGraduateAccount(this.form)" />Unix Account<br />
<input type="checkbox" name="grad_account" id="grad_account3" value="web_host" onclick="checkGraduateAccount(this.form)" />Web Hosting<br />
<input type="checkbox" name="grad_account" id="grad_account4" value="list_server" onclick="checkGraduateAccount(this.form)" />List Server
<p>
<input type="submit" name="submit" value="Submit" />
<input type="reset" name="reset" value="Reset" />
</p>
</form>
</body>
</html>
JavaScript code
function form_validation()
{
//check to see how many elements are on the form
alert(document.account_form.elements.length);
var validatedOK=""; //boolean variable used for return to calling html file
var checked_counter = 0; //use checked_counter to count how many elements on the form
//has passed validation test
with(document.account_form)
{
//note first_name_field is a reference to first name field
var first_name_field = document.getElementById("fname");
//alert(first_name_field.value);
var last_name_field = document.getElementById("lname");
var age_field = document.getElementById("age");
var male_field = (document.getElementById("maleR"));
var female_field = (document.getElementById("femaleR"));
var phone_field = (document.getElementById("phone_num"));
//for loop iteration based on how many elements on the form
// elements.length - 2 you don't want to check last 2
//elements on the form - submit and reset button
for(var i = 0; i<(elements.length - 2); i++)
{
switch(elements[i].name)
{
case "fname":
validatedOK= checkFirstName(first_name_field); //pass a reference to first name field to function
break;
case "lname":
validatedOK= checkLastName(last_name_field);
break;
case "age":
validatedOK= checkAge(age_field);
break;
case "gender":
validatedOK= checkGender();
break;
case "departments":
validatedOK= checkDept();
break;
case "email":
validatedOK= checkEmail();
break;
case "phone_num":
validatedOK= checkPhone(phone_field);
break;
case "class":
validatedOK= checkAccountStatus();
break;
case "undergrad_account":
break;
case "grad_account":
//skip checkbox verification for enable/disable checkbox purpose
break;
default:
alert("no such element exist on the form");
break;
}
//after the switch statement if return value for
//validatedOk is false call a function to return false to html file
//so form won't get submitted
if (!validatedOK)
{
return false;
}
//increment the counter, when all the elements on the form
//has passed validation test, call same function
//return 'true' to html file, so form can be submitted
else
{
checked_counter++; //when checked_counter equals to elements.length - 2
//this means every field has passed validation test
if (checked_counter == elements.length - 2)
{
var status = true;
return status;
}
}
}//end of for loop
}//end of with statement
}//end of form_validation function
/*
function checkAccountStatus
enable/disable graduate account(checkboxes) - base on radio button selection
*/
function disableGraduateAccount(frm)
{
for(var k = 0; k < frm.grad_account.length; k++)
{
frm.grad_account[k].disabled = true;
}
}
function enableGraduateAccount(frm)
{
for(var j = 0; j < frm.grad_account.length; j++)
{
frm.grad_account[j].disabled = false;
}
}
//frm represent form object that contains the under_graduate radio button
function checkAccountStatus(frm)
{
with(document.account_form)
{
var classCtr = -1;
for(var i = 0; i < class.length; i++)
{
if(class[i].checked && class[i].value == 'under_graduate')
{
classCtr = i;
disableGraduateAccount(class[i].form)
}
else if(class[i].checked && class[i].value == 'graduate')
{
classCtr = i;
enableGraduateAccount(class[i].form);
}
}
if(classCtr == -1)
{
alert("you must select either Undergraduate or Graduate radio button.");
return false;
}
else
return true;
}//end of with statement
}
/*
function checkGraduateAccount
*/
function checkGraduateAccount(frm)
{
var gradAccountCtr = 0;
for(var i = 0; i < frm.grad_account.length; i++)
{
if(frm.grad_account[i].checked)
{
gradAccountCtr++;
}
}
if(gradAccountCtr > 2)
alert("graduate students can select only two accounts.");
}
sjcoder07
5-27-07
# 9 Re: disable checkboxes by using getElementByName
Honestly, your validation function is very confusing and far from simple. Since you are working with a simple form, you should just read through the tags using document.getElementById(). As to its functionality, it works fine. What exactly is your problem?
I couldn't figure out how to handle radio buttons inside switch statement inside form_validation function. Since I called checkAccountStatus(this.form) function before form being submitted.
My switch statement suppose to call validation function based on the NAME attribute of the element on the form. If all the elements passed validation test, true is returned; otherwise , false is returned.
Multiple radio buttons can have the same name but the value should be returned for only the one that is checked. The other ones will act as though they don't even exist. What exactly is your problem retrieving them?
# 10 Re: disable checkboxes by using getElementByName
Hello Peej:
My problem is that I want to find a way to keep track how many elements on the form passed validation test.
I can retrived radio buttons by using onclick event handler in html file. but in switch statement I don't have a way to keep track if radio button and checkboxes for undergraduate /graduate student passed validation test or not; Since thesse functions are not invoked by onSubmit event handler
I want to setup a counter that counts how many elements has passed validation test. In the switch statement, var checked_account act as a counter. checked_account got incremented based on value of boolean variable validatedOK, if validatedOK's value is true, increment checked_account increment by 1.
//The case statement for graduate account checkboxes
case "grad_account": //the corresponding check fuction is
break; //checkGraduateAccount(frm)
function checkGraduateAccount invoked by
<input type="checkbox" name="grad_account" id="grad_account1" value="dsl_account" onclick="checkGraduateAccount(this.form)" />DSL Account<br />
checkGraduateAccount is not called when form being submitted(will not get called in the switch statement)
function checkGraduateAccount(frm)
{
var gradAccountCtr = 0;
for(var i = 0; i < frm.grad_account.length; i++)
{
if(frm.grad_account[i].checked)
{
gradAccountCtr++;
}
}
if(gradAccountCtr > 2)
alert("only two accounts available for graduate student.");
else if(gradAccountCtr == 0)
alert("You didn't choose any account. Please select two accounts if you are a graduate student.");
else
checked_counter++; //increment global variable checked_counter
//to keep track of how many elements passed validation test
}
Please suggest a good solution to my problem. thanks!
sjcoder07
5-30-07
# 11 Re: disable checkboxes by using getElementByName
I can retrived radio buttons by using onclick event handler in html file. but in switch statement I don't have a way to keep track if radio button and checkboxes for undergraduate /graduate student passed validation test or not; Since thesse functions are not invoked by onSubmit event handler
As I stated before, you want to use onchange and not onclick. The onclick event will only fire with a mouse. But if the user is keyboard shortcuts, onclick will not fire.
I want to setup a counter that counts how many elements has passed validation test. In the switch statement, var checked_account act as a counter. checked_account got incremented based on value of boolean variable validatedOK, if validatedOK's value is true, increment checked_account increment by 1.
Yet another reason why you should do as I already suggested and drop the with statement. You need to just go through your elements one by one using getElementById(). If something is not validated, return false.
# 12 Re: disable checkboxes by using getElementByName
Hello everyone:
I tried to use a counter to count how many elements passed validation test.
But counter will not increment correctly. I think the cause is due to the value of boolean variable validatedOK didn't get updated correctly!
Since cases for "undergrad_account" and "grad_account " didn't return boolean variable back to switch statement, after the break statement, validatedOK still used value returned by previous case statement function call.
var checked_counter = 0;
function form_validation()
{
with(document.account_form)
{
//note first_name_field is a reference to first name field
var first_name_field = document.getElementById("fname");
//alert(first_name_field.value);
var last_name_field = document.getElementById("lname");
var age_field = document.getElementById("age");
var male_field = (document.getElementById("maleR"));
var female_field = (document.getElementById("femaleR"));
var phone_field = (document.getElementById("phone_num"));
//for loop iteration based on how many elements on the form
// elements.length - 2 you don't want to check last 2
//elements on the form - submit and reset button
for(var i = 0; i<(elements.length - 2); i++)
{
switch(elements[i].name)
{
case "fname":
validatedOK= checkFirstName(first_name_field);
break;
case "lname":
validatedOK= checkLastName(last_name_field);
break;
case "age":
validatedOK= checkAge(age_field);
break;
case "gender":
validatedOK= checkGender();
break;
case "departments":
validatedOK= checkDept();
break;
case "email":
validatedOK= checkEmail();
break;
case "phone_num":
validatedOK= checkPhone(phone_field);
break;
case "class_standing":
validatedOK= checkAccountStatus();
break;
case "undergrad_account":
break;
case "grad_account":
//skip checkbox verification for enable/disable checkbox purpose
break;
case "comments":
validatedOK= checkComments();
break;
default:
alert("no such element exist on the form");
break;
}
//after the switch statement if return value for
//validatedOk is false call a function to return false to html file
//so form won't get submitted
if (!validatedOK)
{
return false;
}
//increment the counter, when all the elements on the form
//has passed validation test, call same function
//return 'true' to html file, so form can be submitted
else
{
checked_counter++;
if (checked_counter == elements.length - 2)
{
var status = true;
return status;
}
}
}//end of for loop
}//end of with statement
}//end of form_validation function
Please give me some suggestions to fix this issue, thanks for your help!
sjcoder07
5-30-07
