JavaScript enable checkboxes

Hi Guys…

What I have is a form and within this form I have a set of checkboxes. There is a master checkbox, which once clicked it should enable all checkboxes and textfields under it.

It will probably be much easier if I give you an example of what I want to achieve.


<input name="enable_bin_ALL" type="checkbox" value="1">&nbsp;
<input type="text" name="buy_it_now_ALL" id="buy_it_now_ALL" class="numfield" disabled="disabled" /> <a href="#" onClick="changeValue('buy_it_now','buy_it_now_ALL','text'); return false;">Fill</a>

When you click on the “enable_bin_ALL” checkbox, it should enable the “buy_it_now_ALL” box and also should enable the following checkbox and textfields:

enable_bin[0]
buy_it_now[0]
enable_bin[1]
buy_it_now[1]


<input name="enable_bin[0]" type="checkbox" value="1" disabled="disabled">&nbsp;
<input type="text" name="buy_it_now[0]" id="buy_it_now[0]" value="" class="numfield" disabled="disabled" />

Any ideas how to achieve this?

Try this:

onchange="var list = ['enable_bin[0]', 'buy_it_now[0]', 'enable_bin[1]', 'buy_it_now[1]']; for(var i=0; i<list.length; i++) document.getElementById(list[i]).checked = this.checked;"

Hi CyberAlien,

Thanks for your suggestion, but I forgot to mention that I need to do it dynamically and there will be a lot more checkboxes to enable than the 2 I posted. I was thinking of making an onClick event, but would like to keep the JavaScript separate in a JavaScript file.

Are there any other checkboxes on that form (ones that should not be changed)? If there are, do any of them start with “enable_” or “buy_it_now”?

Yes, there are other checkboxes in the form, but none of them begin with “enable” or “buy_it_now”.

Then you can just list all form elements, find ones with names starting with “enable” or “buy_it_now” and change their state.

for(var i=0; i<this.form.elements.length; i++)
{
  var el = this.form.elements[i];
  if(el.name && (el.name.substr(0, 6) == 'enable' || el.name.substr(0, 6) == 'buy_it'))
    el.checked = this.checked;
}

Ok so I tried this JavaScript:


function enableBIN(){
    for(var i=0; i<document.addconfig.elements.length; i++)
    {
      var el = addconfig.elements[i];
      if(el.name && (el.name.substr(0, 6) == 'enable' || el.name.substr(0, 6) == 'buy_it'))
        el.checked = document.addconfig.checked;
    }
}

I then triggered it with an onClick event on the master checkbox, but it doesn’t work. Note: I changed this.form to “document.addconfig” as the form has the id/name “addconfig”.

Is this right?

You forgot to replace 2 variables:

document.addconfig.checked should be document.addconfig.enable_bin_ALL.checked
var el = addconfig.elements[i]; should be var el = document.addconfig.elements[i];