jQuery获取checkbox选中的值

jQuery获取checkbox选中的值


1、问题背景

     有几个多选框,选择其中的几个,获取选中的值


2、设计源码

<!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>jQuery获取checkbox选中的值</title>
<script type="text/javascript" src="jquery-2.2.0.js"></script>
<script type="text/javascript">
    $(function(){
		$("input[name='ckb']:checkbox").click(function() {
			var str = "";
			$("input[name='ckb']:checkbox").each(function() {
            	if($(this).is(":checked"))
				{
					str += $(this).attr("value")+",";
				}
       		});
			if(str != null && str.length > 1)
			{
				str = str.substring(0,str.length-1);	
			}
			
			alert(str);
		});
		
	});
</script>
</head>

<body>
   <input type="checkbox" name="ckb" value="1"/>苹果
   <input type="checkbox" name="ckb" value="2"/>橘子
   <input type="checkbox" name="ckb" value="3"/>梨子
   <input type="checkbox" name="ckb" value="4"/>香蕉
</body>
</html>

3、设计结果


原文地址:https://www.cnblogs.com/hzcya1995/p/13314251.html