Reputation: 515
I am just starting out with javascript so please pardon me if my question seems stupid. I want to design a webpage with some checkboxes such that when the first one is checked, the others become enabled. How do I do that using JS? I wrote the following code:
function checkBox() {
if (window.document.form1.mainbox.checked=true) {
for (i=0;i<window.document.form1.Others.length;i++) {
window.document.form1.Others[i].disabled=false;
}
}
else {
for (i=0;i<window.document.form1.Others.length;i++) {
window.document.form1.Others[i].disabled=true;
}
}
}
And this html:
<form name="form1">
<input name="mainbox" value="mainbox" onclick="checkBox()" type="checkbox"> Mainbox<br>
<input disabled="disabled" checked="checked" tabindex="0" name="Others" type="checkbox">No. 1<br>
<input disabled="disabled" checked="checked" tabindex="1" name="Others" type="checkbox"> No. 2<br>
<input disabled="disabled" checked="checked" tabindex="2" name="Others" type="checkbox"> No. 3<br>
</form>
The problem is that on the first click the other checkboxes do become enabled, but nothing happens on the subsequent clicks, i.e. they do not become disabled again. How do I correct this problem? Any help will be appreciated. Thanks!
EDIT
I followed the suggestion of gabitzish and it worked. However, I now want to pass Others as a parameter, so I write:
<input name="mainbox" value="mainbox" onclick="checkBox(Others)" type="checkbox"> Mainbox<br>
and modify the script as follows:
window.checkBox = function(chkname) {
if (window.document.form1.mainbox.checked==true) {
for (i=0;i<window.document.form1.chkname.length;i++) {
window.document.form1.chkname[i].disabled=false;
}
}
else {
for (i=0;i<window.document.form1.chkname.length;i++) {
window.document.form1.chkname[i].disabled=true;
}
}
}
But this does not work. Please help me out here. I will be very thankful.
Upvotes: 0
Views: 1135
Reputation: 9691
I've created a jsFiddle with your code, and some minor changes : http://jsfiddle.net/CUeDg/1/
The problem with the original code was that checkBox() function was not found on click.
Edit: Here is a solution to later edit of your question: http://jsfiddle.net/CUeDg/3/ I've passed the param to the function as a string.
Later edit: I suspect that you need that param to know what set of checkboxes you need to toggle. I made a jsFiddle for that too: http://jsfiddle.net/CUeDg/5/ (If I suspected wrong, don't consider this part of the answer)
Upvotes: 1
Reputation: 9286
this line is at fault (your missing a =)
if (window.document.form1.mainbox.checked=true)
try changing it to
if (window.document.form1.mainbox.checked)
Upvotes: 2