Задача: выделить чекбоксы в форме, которые имеют имена типа box[].
Решение:
function SetAllCheckBoxes(FormName, FieldName, CheckValue) { if(!document.forms[FormName]) return; var objCheckBoxes = document.forms[FormName].elements[FieldName]; if(!objCheckBoxes) return; var countCheckBoxes = objCheckBoxes.length; if(!countCheckBoxes) objCheckBoxes.checked = CheckValue; else // set the check value for all check boxes for(var i = 0; i < countCheckBoxes; i++) objCheckBoxes[i].checked = CheckValue; }
пример:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Документ без названия</title> <script language="javascript"> function SetAllCheckBoxes(FormName, FieldName, CheckValue) { if(!document.forms[FormName]) return; var objCheckBoxes = document.forms[FormName].elements[FieldName]; if(!objCheckBoxes) return; var countCheckBoxes = objCheckBoxes.length; if(!countCheckBoxes) objCheckBoxes.checked = CheckValue; else // set the check value for all check boxes for(var i = 0; i < countCheckBoxes; i++) objCheckBoxes[i].checked = CheckValue; } </script> </head> <body> <form id="form1" name="form1" method="post" action=""> чекбокс 1<input type="checkbox" name="box[]" id="box[]" /> чекбокс 2<input type="checkbox" name="box[]" id="box[]" /> чекбокс 3<input type="checkbox" name="box[]" id="box[]" /> чекбокс 4<input type="checkbox" name="box[]" id="box[]" /> чекбокс 5<input type="checkbox" name="box[]" id="box[]" /> чекбокс 6<input type="checkbox" name="box[]" id="box[]" /> чекбокс 7<input type="checkbox" name="box[]" id="box[]" /> </form> <br /> <a onclick="SetAllCheckBoxes('form1', 'box[]', true)" style="cursor:pointer;">Выделить все чекбоксы</a> <a onclick="SetAllCheckBoxes('form1', 'box[]', false)" style="cursor:pointer;">Снять все чекбоксы</a> </body> </html>