Note that there are some explanatory texts on larger screens.

plurals
  1. POEnable checkboxes using Javascript
    text
    copied!<p>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:</p> <pre><code>function checkBox() { if (window.document.form1.mainbox.checked=true) { for (i=0;i&lt;window.document.form1.Others.length;i++) { window.document.form1.Others[i].disabled=false; } } else { for (i=0;i&lt;window.document.form1.Others.length;i++) { window.document.form1.Others[i].disabled=true; } } } </code></pre> <p>And this html:</p> <pre><code>&lt;form name="form1"&gt; &lt;input name="mainbox" value="mainbox" onclick="checkBox()" type="checkbox"&gt; Mainbox&lt;br&gt; &lt;input disabled="disabled" checked="checked" tabindex="0" name="Others" type="checkbox"&gt;No. 1&lt;br&gt; &lt;input disabled="disabled" checked="checked" tabindex="1" name="Others" type="checkbox"&gt; No. 2&lt;br&gt; &lt;input disabled="disabled" checked="checked" tabindex="2" name="Others" type="checkbox"&gt; No. 3&lt;br&gt; &lt;/form&gt; </code></pre> <p>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!</p> <p><b>EDIT</b></p> <p>I followed the suggestion of gabitzish and it worked. However, I now want to pass Others as a parameter, so I write:</p> <pre><code>&lt;input name="mainbox" value="mainbox" onclick="checkBox(Others)" type="checkbox"&gt; Mainbox&lt;br&gt; </code></pre> <p>and modify the script as follows:</p> <pre><code>window.checkBox = function(chkname) { if (window.document.form1.mainbox.checked==true) { for (i=0;i&lt;window.document.form1.chkname.length;i++) { window.document.form1.chkname[i].disabled=false; } } else { for (i=0;i&lt;window.document.form1.chkname.length;i++) { window.document.form1.chkname[i].disabled=true; } } } </code></pre> <p>But this does not work. Please help me out here. I will be very thankful.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload