Help with code to selectively tick form checkboxes

Hi all,

I’m new to these forums, and a complete novice when it comes to Javascript, so I thought I’d dive right in and ask a question that I hope someone can help me answer.

A web page I’m creating will allow a visitor to download a number of PDF files. A form on the page has one checkbox for each of the PDF files. I also wanted to add a checkbox to select/deselect all the PDFs.
I hunted around the web and found the following Javascript code:

function checkedAll (frm1) {
	var aa= document.getElementById('pdf_form');
	 if (checked == false)
          {
           checked = true
          }
        else
          {
          checked = false
          }
	for (var i =0; i < aa.elements.length; i++) 
	{
	 aa.elements[i].checked = checked;
	}
}

My form has an ID of pdf_form and I call the above code from the onclick event of the select all/deselect all checkbox:

<p><input name="checkall" type="checkbox" class="pdf_checkbox" value="" onclick='checkedAll(pdf_form);' /> Select / Deselect all</p>

All works fine, but I also want the visitor to supply their name and email address before downloading, so I want to add another checkbox before the submit button to allow them to opt in/out of having their email address used for further mail shots.

Unfortunately since the code selects/deselects all checkboxes on the form, it also ticks/unticks the opt in/out checkbox.

Is there a way - possibly by targeting the opt in/out checkbox’s ID - to filter it out of this mass selection/de-selection process?

I’m sure it’s pretty straightforward but as I say I’m a Javascript novice.

Thanks in advance,
Tony.

When working with form elements the name of the elements should be used, and not their identifiers.

Do the names of the checkboxes that you want selected have a common pattern that you can take advantage of?

If not, can they be grouped together in some way, such as in a fieidset.

If not, can you group them together in some other way (such as a div)

If not, you can check that the checkbox is not the opt-in/out one.

I could do that quite easily, say give the DIV an ID of pdfWrapper for instance.

If so, how would I change the Javascript to accommodate that?

Thanks for your help,
Tony.

Currently you’re using the aa reference to the form to get the form elements.

You’ll want to change aa so that so you only get the inputs from within the pdfWrapper section instead.


aa = document.getElementById('pdfWrapper').getElementsByTagName('input');

Then instead of using aa.elements (because you’re not dealing with the whole form anymore) you can use aa.length in the for loop condition, and aa[i] within the loop.

I would also rename aa throughout the code to be a more meaningful variable, such as pdfInputs

Thanks very much for that solution pmw57, it worked beautifully :slight_smile: