根据类别选择全部

时间:2010-08-31 07:01:19

标签: javascript arrays checkbox

  function Check(chk)  
    {  
       if(document.myform.brandid.value!="Check all"){  
        for (i = 0; i < chk.length; i++)  
        chk[i].checked = true ;  
        document.myform.brandid.value="UnCheck all";  
       }else{  
        for (i = 0; i < chk.length; i++)  
            chk[i].checked = false ;  
            document.myform.brandid.value="Check all";  
       }  
    }  

我的表格包含:

--category FRUITS --  
 checkbox for Select All   
 checkbox for Apple  
 checkbox for Mango  

--category VEGETABLES--  
 checkbox for Select All   
 checkbox for Carrots  
 checkbox for Cabbage  

如何选择所有选项,只会根据类别类型选择其下的所有项目。如果我选中第一个选择全部属于类别水果,只有Apple和Mango项目会选中复选框吗?

1 个答案:

答案 0 :(得分:0)

首先创建表单并添加一个类来标记组元素

<form name="my_form" id="my_form">
<h1>Fruits</h1> 
    <input type="checkbox" value="" id="all_fruits" /> Select All <br />
    <input type="checkbox" value="Apple" class="fruits" /> Apple <br />
    <input type="checkbox" value="Apple" class="fruits" /> Mango

<h1>VEGETABLES</h1> 
    <input type="checkbox" value="" id="all_veges" /> Select All <br />
    <input type="checkbox" value="Carrots" class="veges" /> Carrots <br />
    <input type="checkbox" value="Cabbage" class="veges" /> Cabbage
</form>

然后创建一个不显眼的功能来处理所需的操作

function Check() {  
  var allFruits = document.getElementById('all_fruits'), 
  allVeges = document.getElementById('all_veges'), 
  formElems = document.forms.my_form.elements;

  allFruits.onclick = function() {   // attach a click event to the first group (fruits)
  if (allFruits.checked) {        // if SELECT ALL is clicked
     for (var i = 0; i < formElems.length; i++) {  // loop over all form elements
        if ( formElems[i].type === 'checkbox' && formElems[i].className === 'fruits' ){ // if a checkbox has a class of fruits
           formElems[i].checked = true;  // check it
        }
     }
   }
  else {  // if SELECT ALL is unchecked 
     for (var i = 0; i < formElems.length; i++) {  // loop over all form elements 
        if ( formElems[i].type === 'checkbox' && formElems[i].className === 'fruits' ) { // if a checkbox has a class of fruits
           formElems[i].checked = false;  // uncheck it
        }
      }
    }
   };

  // do the same for vegetables 
  allVeges.onclick = function() {
  if(allVeges.checked){
     for (var i = 0; i < formElems.length; i++) {
        if ( formElems[i].type === 'checkbox' && formElems[i].className === 'veges' ){
           formElems[i].checked = true;
        }
     }
   }
  else {
     for (var i = 0; i < formElems.length; i++) {
        if ( formElems[i].type === 'checkbox' && formElems[i].className === 'veges' ){
           formElems[i].checked = false;
        }
      }
    }
   };
}

window.onload = Check;  // activate function