View Full Version : Using buttons to check and uncheck checkboxes

12-07-2010, 11:11 PM
I'm trying to write some code that uses buttons to check and uncheck certain checkboxes. I am stumped and all the code I have been finding is using for loops to check or uncheck all the boxes, when I just want to check or uncheck certain ones.

Here's an example of the type of function I'm trying to use:

function checkSome (form) {
document.myForm.list.one.checked = true;
document.myForm.list.two.checked = true;
document.myForm.list.three.checked = false;

And the button:

<input type="button" value="Option 1" onClick="checkSome(this.form)"/>

Old Pedant
12-07-2010, 11:39 PM
What was "list." in there for???

function checkSome (form) {
form.one.checked = true;
form.two.checked = true;
form.three.checked = false;

Assuming, that is, that you had

<input type="checkbox" name="one" />
<input type="checkbox" name="two" />
<input type="checkbox" name="three" />

12-07-2010, 11:58 PM
The form I am using has several different inputs (not just the checkboxes) so I have

<input type="checkbox" name="list" value="one"/>
<input type="checkbox" name="list" value="two"/>
<input type="checkbox" name="list" value="three"/>

From my understanding I would have to have:

function checkSome (form) {
form.list.one.checked = true;
form.list.two.checked = true;
form.list.three.checked = false;
But it's still not working.

Philip M
12-08-2010, 08:50 AM
You are confusing the value of the checkbox with its name and index.

function checkSome (form) {
form.list[0].checked = true;
form.list[1].checked = true;
form.list[2].checked = false;

Remember that the index starts at 0 (the first checkbox in the group list is list[0]).

Obama can't be himself because of who he is. But now he is who he is. - Political commentator, BBC 2.