jQuery实现获取选中复选框的值

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Jquery复选框练习</title>
<!-- 引入jQuery,引入你自己的jQuery文件 -->
<script type="text/javascript" src="jquery.min.js" ></script>
</head>
<body>
<div>
<p>选择要购买的水果</p>
<ul id="fruit">
<li><input type="checkbox" name='message' value="001"/>苹果</li>
<li><input type="checkbox" name='message' value="002"/>雪梨</li>
<li><input type="checkbox" name='message' value="003"/>芒果</li>
<li><input type="checkbox" name='message' value="004"/>菠萝</li>
</ul>
<input type="checkbox" id="All"/>
<button id="checkAll">全选</button>
<button id="nothing">全不选</button>
<button id="reverseAll">反选</button>
<button class="chooseFruit">购买</button>

<script type="text/javascript">

<!-- 选择全部/全不选 -->
$("#All").click(function(){
if("this.checked"){
$("#fruit :checkbox").prop("checked", true);
}else{
$("#fruit :checkbox").prop("checked", false);
}
});

<!--选择全部-->
$("#checkAll").click(function(){
$("#fruit :checkbox").prop("checked", true);
});

<!--全不选-->
$("#nothing").click(function(){
$("#fruit :checkbox").prop("checked", false);
});

<!--反选-->
$("#reverseAll").click(function(){
$("#fruit :checkbox").each(function(i){
$(this).prop("checked", !$(this).prop("checked"));
});
});

<!--获取选中复选框的值-->
$(".chooseFruit").click(function(){
var arr = new Array();
$("#fruit input:checkbox[name='message']:checked").each(function(i){
arr[i] = $(this).val();
});
var vals = arr.join(",");
console.log(vals,222);
});
</script>
</div>
</body>
</html>

posted @ 2018-12-18 12:05  FancyAnnaYL  阅读(7596)  评论(0编辑  收藏  举报