天天看點

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">

<!--

$("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="">

<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>

本文轉自linzheng 51CTO部落格,原文連結:http://blog.51cto.com/linzheng/1081658

繼續閱讀