jQuery复选框实现全选、全不选、反选、获取选项值

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>复选框</title>
    <script src="../js/jquery-3.1.1.js"></script>
    <script>
        $(document).ready(function(){
        	//全选/全不选
        	$("#selectAll").change(function(){
       			$("input[name='items']").prop("checked",this.checked);
       		});
       		
        	//全选
        	$("#checkedAll").click(function(){
        		$("input[name='items']").prop("checked",true);
        	});
        	//全不选
        	$("#checkedNo").click(function(){
        		$("input[name='items']").prop("checked",false);
        	});
        	//反选
        	$("#checkRev").click(function(){
        		$("input[name='items']").each(function(){
        		this.checked=!this.checked;
        		});
        	});
        	//获得选项的值
        	$("#checkValue").click(function(){
        		var result="";
        		$("input[name='items']").each(function(){
        			if(this.checked){
        				result+=$(this).val()+"\n";
        			}
        		});
        		alert(result);
        	});
        });
    </script>
    <style>
        .container {
            margin: 0px auto;
            width: 500px;
        }
    </style>
</head>
<body>
    <div class="container">
        <label>你爱好的运动是?</label>
        <p>
            <input type="checkbox" name="items" value="足球" />足球
            <input type="checkbox" name="items" value="篮球" />篮球
            <input type="checkbox" name="items" value="排球" />排球
            <input type="checkbox" name="items" value="台球" />台球
        </p>
        <p>
            <input type="checkbox" id="selectAll" value="0" />全选
            <input type="button" id="checkedAll" value="全选" />
            <input type="button" id="checkedNo" value="全不选" />
            <input type="button" id="checkRev" value="反选" />
            <input type="button" name="name" id="checkValue" value="获得选中值" />
            <input type="button" id="submit" value="提交" />
        </p>
    </div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_43708090/article/details/84840915
今日推荐