获取选中值代码:

<input type="checkbox"  value="1" name="assess_mode" >
<input type="checkbox"  value="2" name="assess_mode" >

function getValueCB(nodestr){
	var node = document.getElementsByName(nodestr);
	var nodeValue = [];
	var len = node.length;
	for (var i = 0; i < len; i++) {
	 	if (node[i].checked) {
			nodeValue.push(node[i].value);
	 	}
	}
	return nodeValue;
}

getValueCB("assess_mode")


.
设置选中状态代码:

//values是上面获取选中值是存储的数组
function fillCB(values, nodestr){
	var node = document.getElementsByName(nodestr);
	var len = node.length;
	console.log(values);
	for (var i = 0; i < len; i++) {
		console.log(node[i].value);
	 	if (values.indexOf(node[i].value) > -1) {
			node[i].checked = true;
	 	}
	}
}

另外实时监听checkbox值变化的方法如下:

//这是监听页面上所有的checkbox控件点击事件
$(function() {
	$("input:checkbox").each(function () {
		$(this).click(function () {
		//console.log($(this))
		if ($(this)[0].checked == true) {
			console.log($(this).val());
		}
	})
});

//这只监听页面上name为assess_mode的一组checkbox控件点击事件
$(function() {
	$("input:checkbox[name='assess_mode']").each(function () {
		$(this).click(function () {
		//console.log($(this))
		if ($(this)[0].checked == true) {
			console.log($(this).val());
		}
	})
});

本人开发中遇到一个bug,上述方法一直无效,,原来是因为copy代码的时候,原来的代码就定义了name字段,自己又重新定义了一个name字段,变成定义了2个name,搞得 程序执行,结果一直异常!!

参考
https://blog.csdn.net/liuminyi1987/article/details/80609879

https://blog.csdn.net/qq_42729390/article/details/88928970

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐