原生checkbox多选框默认选中以及获取选中的结果

最终效果:

代码如下 

<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<meta http-equiv="X-UA-Compatible" content="ie=edge" />
	<title>多选框的各种操作</title>
	<style type="text/css">
		.box{margin:50px auto;width:500px;}
		input{width:30px;height:30px;display:inline-block;}
		.box2 div.on{background:red;}
	</style>
</head>
<body>
	<div class="box">
		<div class="box1">
			<input type="checkbox" name="001" id="001" value="" />
			<input type="checkbox" name="002" id="002" value="" />
			<input type="checkbox" name="003" id="003" value="" />
			<input type="checkbox" name="004" id="004" value="" />
			<input type="checkbox" name="005" id="005" value="" />
			<a class="box1-btn" href="javascript:;">获取</a>
		</div>
		
		<div class="box2">
			<div>
			<input type="checkbox" name="006" id="006" value="" />
			</div>
			
			<div>
			<input type="checkbox" name="007" id="007" value="" />
			</div>
			
			<div>
			<input type="checkbox" name="008" id="008" value="" />
			</div>
			
			<div>
			<input type="checkbox" name="009" id="009" value="" />
			</div>
			
			<div>
			<input type="checkbox" name="010" id="010" value="" />
			</div>
		</div>
	</div>	
</body>
</html>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
	$(function(){
		//获取所选中元素的id-S
		$('.box1-btn').click(function(){
			var result_1 = '';
			$('.box1 input').each(function(){
				if($(this).is(':checked')){
					result_1+=$(this).attr('id')+','
					console.log(result_1)
				}
				
			});
		});
		//获取所选中元素的id-E
		
//		根据ID选中对应的元素-S
		var arr = ["006","008"];
		for(var i=0;i<arr.length;i++){
			$('#'+arr[i]).attr('checked',true).parent('div').addClass('on');//这是jq的写法
			
//			下面这两个都是ES6语法(用到了es6中的新增特性:模板对象)
			//$(`#${arr[i]}`).attr('checked',true).parent('div').addClass('on')
			//$(`#${arr[i]}`).parent('div').addClass('on')	因为把这段集合到上面了,所以可以注释了
		}
//		根据ID选中对应的元素-E
	});
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值