博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

jquery如何判断checkbox(复选框)是否被选中(ie8 火狐)

Posted on 2011-01-12 21:33  itcfj  阅读(3899)  评论(0编辑  收藏  举报

 jquery如何判断checkbox(复选框)是否被选中



谁都知道 在html 如果一个复选框被选中 是 checked="checked"。

但是我们如果用jquery alert($("#id").attr("checked")) 会提示您是true而不是checked

所以很多朋友判断  if($("#id").attr("checked")=="true") 这个是错误的,其实应该是 if($("#id").attr("checked")==true)


例子里面包括了一下几个功能。

   <input type="button" id="btn1" value="全选">
   <input type="button" id="btn2" value="取消全选">
   <input type="button" id="btn3" value="选中所有奇数">
   <input type="button" id="btn4" value="反选">
   <input type="button" id="btn5" value="获得选中的所有值">

代码

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <SCRIPT LANGUAGE="JavaScript" src="http://www.cnjquery.com/demo/jquery.js"></script >
  <SCRIPT LANGUAGE="JavaScript">
  <!--
   $("document").ready(function(){
  
    $("#btn1").click(function(){
   
    $("[name='checkbox']").attr("checked",'true');//全选
 
    })
       $("#btn2").click(function(){
   
    $("[name='checkbox']").removeAttr("checked");//取消全选
 
    })
    $("#btn3").click(function(){
   
    $("[name='checkbox']:even").attr("checked",'true');//选中所有奇数
 
    })
    $("#btn4").click(function(){
   
    $("[name='checkbox']").each(function(){
   
 
     if($(this).attr("checked"))
   {
    $(this).removeAttr("checked");
  
   }
   else
   {
    $(this).attr("checked",'true');
  
   }
 
    })
 
    })
     $("#btn5").click(function(){
    var str="";
    $("[name='checkbox'][checked]").each(function(){
     str+=$(this).val()+""r"n";
   //alert($(this).val());
    })
   alert(str);
    })
   })
  //-->
  </SCRIPT>
 
 </HEAD>

 <BODY>
 <form name="form1" method="post" action="">
   <input type="button" id="btn1" value="全选">
   <input type="button" id="btn2" value="取消全选">
   <input type="button" id="btn3" value="选中所有奇数">
   <input type="button" id="btn4" value="反选">
   <input type="button" id="btn5" value="获得选中的所有值">
   <br>
   <input type="checkbox" name="checkbox" value="checkbox1">
   checkbox1
   <input type="checkbox" name="checkbox" value="checkbox2">
   checkbox2
   <input type="checkbox" name="checkbox" value="checkbox3">
   checkbox3
   <input type="checkbox" name="checkbox" value="checkbox4">
   checkbox4
   <input type="checkbox" name="checkbox" value="checkbox5">
   checkbox5
   <input type="checkbox" name="checkbox" value="checkbox6">
   checkbox6
   <input type="checkbox" name="checkbox" value="checkbox7">
   checkbox7
   <input type="checkbox" name="checkbox" value="checkbox8">
 checkbox8
 </form>

 

 

/************单个checkbox全选************************/

function clickCheckbox() {
           if($("#checkPathAll").attr("checked"))
           {
             $("input[name='checkPath']").each(function() {
                 $(this).attr("checked", true);
             });
           }
           else
           {
             $("input[name='checkPath']").each(function() {
                 $(this).attr("checked", false);
             });        
           }
        }







var dlg;
$( document ).ready( function()
{

   // 删除按钮事件开始 ----------------------------------------------------------------------
   $("#bottomdelete" ).click( function()
   {
   
        var str="";
        $("[name='listcheck'][checked]").each(function()
        {
      
           if( str == "" )
           {
              str = $( this ).val();
           }
           else
           {
              str += "," + $( this ).val()
           }
      
        })
       
        if(str==""||str==null)
        {
          alert( "请您选择要删除的记录!" );
        
          return false;
        }
        else
        {
            if( confirm("您确定要删除所选的理财吗?" ) )
            {
               document.getElementById("deleteid").value=str;
               doSubmit();
            }
            else
            {
              $(":check").removeAttr("checked");//取消全选
               $( "#bottomSelectAll" ).val( "全选" );
              return false;
            }
        }

   }
   )

   // 删除按钮事件结束 ----------------------------------------------------------------------


       // 修改
       $( ".update" ).each( function()
       {
          $( this ).click( function()
          {
           var moneyArray = $( this ).attr( "accesskey" ).split( ',' );
          
//           $("#firame").attr("src","addMoney.aspx?id="+ moneyArray[0]+"&date="+moneyArray[1]+"&selectType="+moneyArray[3]+"&money="+ moneyArray

[4]+"&comment="+moneyArray[5]+"&inout="+moneyArray[2]+"&userid="+document.getElementById("idHiddle").value)
//          var dlg=$("#firame").xDlg(
//          {
//           pos:{left:"200",top:"400"},
//           size:{width:"403px",height:"320px"},   
//           buttons:null,
//           onCancel : function()
//            {
//              window.location.reload()  
//            } 
//                                          
//          });
            if(dlg!=null)
            {
               dlg.close();
            }
           dlg=$.topWnd().$.xDlg({
            pos:"center",
           size:{width:"403px",height:"320px"},   
           buttons:null,
            fra:"/pages/mymoney/addMoney.aspx?id="+ moneyArray[0]+"&date="+moneyArray[1]+"&selectType="+moneyArray[3]+"&money="+ moneyArray

[4]+"&comment="+moneyArray[5]+"&inout="+moneyArray[2]+"&userid="+document.getElementById("idHiddle").value,
           onCancel : function()
            {
              window.location.reload()  
            } 
         
           });
           dlg.setCaption("修改记录");
           dlg.canScroll(false);

         }
          )

       }
       )
  
   })



  


var selectAll = function ( selectid, button )
{

   if( button == null )
   {

      if( $( "#" + selectid + "" ).attr( "checked" ) == true )
      {

          $("input[name='listcheck']").each(function()
         {
             $(this).attr("checked", true);
         });
      }
      else
      {
         $("input[name='listcheck']").each(function()
         {
             $(this).attr("checked", false);
         });
      }
   }
   else
   {
      if( $( "#" + selectid + "" ).val() == "全选" )
      {
        $("[name='listcheck']").attr("checked",'true');//全选
       $( "#" + selectid + "" ).val( "反选" );
      }
      else
      {
        $("[name='listcheck']").removeAttr("checked");//取消全选
         $( "#" + selectid + "" ).val( "全选" );
      }

   }
}
 var deleteMoney=function(id)
 {
  if(confirm("您确定要删除此理财吗?"))
  {
       document.getElementById("deleteid").value=id;
       doSubmit();
   }
 }
   function doSubmit()
   {
     Form1.submit();
   }
   var realnumber=function(number)
   {
      return  /^-?\d+(\.\d+)?$/.test(number);
   }   
   
function hidenodata()
   {
      document.getElementById("nodata").style.display="none";
      document.getElementById("topfenye").style.display="none";
      document.getElementById ("bottomfy").style.display="none";
      document.getElementById("zi14").style.display="block";
   }
 function addClass()
{
        if(dlg!=null)
        {
            dlg.close();
         }

         var id =document.getElementById("idHiddle").value;
        dlg=$.topWnd().$.xDlg({
            pos:"center",
           size:{width:"403px",height:"320px"},   
           buttons:null,
            fra:"/pages/mymoney/addMoney.aspx?userid=" + id,
           onCancel : function()
            {
              window.location.reload()  
            } 
         
           });
           dlg.setCaption("添加记录");
           dlg.canScroll(false);
//    $("#firame").attr("src","addMoney.aspx?userid=" + id)
//   
//      dlg=$("#firame").xDlg(
//      {
//       pos:{left:"200",top:"400"},
//       size:{width:"403px",height:"320px"},  
//       buttons:null ,
//       onCancel : function()
//        {
//          window.location.reload()  
//        }                           
//        });
//    dlg.setCaption("添加记录");
      

}
    function getStringUTFLength(str) {
    var value = str.replace(/[^\x00-\xff]/g," ");
    return value.length;
}

function leftUTFString(str,len) {
    if(getStringUTFLength(str)<=len)
        return str;
    var value = str.substring(0,len);

    while(getStringUTFLength(value)>len) {
        value = value.substring(0,value.length-1);
    }
    return value;
}

function count() {
    var value = document.getElementById("comment").value;
    value = value.replace(/[\u4e00-\u9fa5]/g," ");
    if(value.length>=50) {
        with(window.event) {
            cancelBubble = true;
            keyCode=0;
            returnValue = false;
        }
        document.getElementById("comment").value = leftUTFString(document.getElementById("comment").value,50);
    }
}
    /*清除*/
function clearfrm()
{
    document.all.comment.value="";
    document.all.TxbMoney.value="";
    return;
}
function subFrm()
{
  
    if (document.all.txdate.value=="")
    {
        alert("时间不能为空");
        document.all.txdate.focus();
        return false;
    }
    if(!CheckDate(document.all.txdate.value))
    {
      return false;
    }

    if (document.all.TxbMoney.value=="")
    {
        alert("金额不能为空");
        document.all.TxbMoney.focus();
        return false;
    } 
    if (!IsDblNumber(document.all.TxbMoney.value))
    {
        return false;
    }
}
function CheckDate(strDate)
{
    var reg=/^(\d{4})([-])(\d{2})([-])(\d{2})/;
    if(!reg.test(strDate))
    {
        alert("时间格式不正确!");
        return false;
    }
    else
    {
      return true;
    }
}
function trim(stringToTrim)
{
   return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function   IsDblNumber(passedVal) 
  { 
  var   sign=0; 
  var   flag="¥"; 
  var   price; 
  if   (passedVal   ==   ""){return   "";} 
  //if(passedVal=="0"){return   "¥00.00";} 
  for   (i=0;   i<passedVal.length;   i++) 
  { 
  if   ((passedVal.charAt(i)   ==   ".")||(passedVal.charAt(i)   ==   ".")){i++;sign=sign+1;} 
  if   ((passedVal.charAt(i)   ==   "$")||(passedVal.charAt(i)   ==   "¥")){i++;} 
  if   (passedVal.charAt(i)   <   "0"){alert("请输入正确的金额");return   false;} 
  if   (passedVal.charAt(i)   >   "9"){alert("请输入正确的金额");return   false;} 
  } 
  //alert(passedVal);alert(parseInt(passedVal,10)); 
  
  if(sign>=2){alert("请输入正确的金额");return   false;} 
  if(passedVal.charAt(0)   ==   flag) 
  price=passedVal.substr(1,passedVal.length-1); 
  
  else   
  price=passedVal.substr(0,passedVal.length); 
  //alert(price); 
  if((parseInt(price,10)>9999999)||(parseInt(price,10)<-9999999)){alert("您输入的金额超出范围,金额最大不能超过9999999");return   false;} 
  pricelen=price.length; 
  dotplace=price.indexOf("."); 
  //alert(dotplace); 
  if   (dotplace==-1) 
  { 
  return(flag+price+".00") 
  } 
  if   ((pricelen-dotplace)==2) 
  { 
  return(flag+price+"0"); 
  } 
  if   ((pricelen-dotplace)>=3) 
  { 
  if(parseInt(price.charAt(dotplace+3))>=5) 
  { 
  var   temp=price.substr(0,dotplace+3) 
    price=parseFloat(temp)+0.01; 
    //var   NewNumber=New   Number(price); 
    var   tempp=price.toString(10) 
    var   dotp=tempp.indexOf("."); 
    if(dotp==-1)return(flag+tempp+".00"); 
  return(flag+price); 
  } 
  
  return(flag+price.substr(0,dotplace+3)) 
  } 
  return   true; 
  }
 function editClass()
{
   var tempUnit ="money";
   var id =document.getElementById("addidHiddle").value;
    dlg= $.topWnd().$.xDlg(
   {
      pos : "CENTER",
      size :
      {
         width : "625px", height : "310px"
      }
      ,
      fra : "http://www.cnblogs.com/UserControl/Compnent/fenlei.aspx?flag=" + tempUnit + "&id=" + id,
      buttons : null , onCancel : function()
      {
         var html=dlg.body.find("iframe").contents().find("#expose").val();//获取分类
            var str= new Array();   
            var opt="";
            str= html.split("#");
            if(str.length>0)
            {
                for(i=str.length-2;i>=0;i--)
                {
                    opt+="<option value='"+str[i].split('|')[0]+"'>"+str[i].split('|')[1]+"</option>"
                }
                $("#dropType").get(0).options.length = 0;  //清空selec
                $("#dropType").append(opt);//重新复制
            }
      }
   }
   );
   dlg.setCaption( "分类管理" );
   $.topWnd().dlg=dlg;
}
function ReClose()
{
   if(dlg!=null && typeof(dlg.isNull)!="undefined" && !dlg.isNull)dlg.close();
   top.frames['mainFra'].location.reload();
}