发布旅游信息的时候,有个旅游类型,是多选,怎么验证未选?(至少选一项。)
<form id="form1" name="form1" method="post" action="" onsubmit="return checkForm()">
  <input name="lx" type="checkbox" id="lx" value="休闲游" /> 休闲游
  <input name="lx" type="checkbox" id="lx" value="美食游" /> 美食游
  <input name="lx" type="checkbox" id="lx" value="风景游" /> 风景游
  <input name="lx" type="checkbox" id="lx" value="健身游" /> 健身游
  <input name="lx" type="checkbox" id="lx" value="购物游" /> 购物游
  <input type="submit" name="Submit" value="提交" />
</form>这个checkForm函数怎么验证名为lx的checkbox为空?下面的写法不行。
if(document.form1.lx.value==""){
alert("至少选择一项!");
return false
}

解决方案 »

  1.   

    funtion checkForm() {
         var cbs = document.getElementsByName("lx");
         var tag = false; 
         for(var cb in cbs) {
            if(cb.checked) {
               tag = true; 
            }
         }
         if(!tag) {
            alert("至少选择一项");
            return false;
         }
    }
      

  2.   


    if (document.form1.lx.length){
       var b = false;
       for(var i=0; i<document.form1.lx.length; i++){
          if(document.form1.lx[i].value!=""){
              b = true;
              break;
          }
       }
       if(!b){
           alert("至少选择一项!");
           return false
       }
    }
    else{
       if(document.form1.lx.value==""){
           alert("至少选择一项!");
           return false
       }
    }
      

  3.   

    看错了/ 改一下:if (document.form1.lx.length){
       var b = false;
       for(var i=0; i<document.form1.lx.length; i++){
          if(document.form1.lx[i].checked){
              b = true;
              break;
          }
       }
       if(!b){
           alert("至少选择一项!");
           return false
       }
    }
    else{
       if(document.form1.lx.checked){
           alert("至少选择一项!");
           return false
       }
    }
      

  4.   


    if ($('input[:checked]').length ==0)
    //为空,一个都没选中 do sth.
    else
    //至少选中一个,do sth.
      

  5.   

    呵呵,谢谢诸位,
    测试了一下1楼的,可以的,但是在alert后,怎么把焦点返回到第一个checkbox的位置呢?使用document.form1.lx.focus()不好使啊。