(编辑:jimmy 日期: 2024/11/16 浏览:2)
通过value值设置checkbox选中
html
<input type="checkbox" name="ChekRole" value="1" >超级管理员 <input type="checkbox" name="ChekRole" value="2">学生 <input type="checkbox" name="ChekRole" value="3">教师
js实现代码
<script type="text/javascript"> var name = "1,2,3"; var names = name.split(","); var inputs = document.getElementsByTagName('input'); for (var i =0;i<inputs.length;i++) { for (var n =0;n<names.length;n++) { if (names[n]===inputs[i].value) { inputs[i].checked = true; } } } </script>
jquery实现代码
<script type="text/javascript"> var name = "1,2"; $(name.split(",")).each(function (i,e){ $("input[name='ChekRole'][value='"+e+"']").prop("checked",true); }) </script>
id值设置checkbox选中
html
<input type="checkbox" id="test1" name="ChekRole" value="1" >超级管理员 <input type="checkbox" id="test2" name="ChekRole" value="2">学生 <input type="checkbox" id="test3" name="ChekRole" value="3">教师
js实现代码
<script type="text/javascript"> document.oncontextmenu = function(){return false;} var name = "test1,test2" var names = name.split(",") var inputs = document.getElementsByTagName('input') for (var i =0;i<inputs.length;i++) { for (var n =0;n<names.length;n++) { if (names[n]===inputs[i].id) { inputs[i].checked = true; } } } </script>
jquery实现代码
<script type="text/javascript"> var name = "test1,test2"; $(name.split(",")).each(function (i,e){ $("input[name='ChekRole'][id='"+e+"']").prop("checked",true); }) </script>
通过数值对应给checkbox的设置默认属性值(勾选状态)
//初始化默认已拥有的权限 $(function () { /* 获取所有复选框的值 var box = document.getElementsByName("user-Character-0-0-0"); var objArray = box.length; var chestr=""; for(var i=0;i<objArray;i++){ chestr+=box[i].value+","; } alert(chestr);*/ var roleName = $("#roleName").val();//获取需要初始化的数值 //把已经拥有的复选框的属性值变成true var arrStr = roleName.split(",");//转化成数组 for (var i = 0; i < arrStr.length; i++) { $("input[Value=" + arrStr[i] + "]").attr("checked", "checked");//根据value给checkbox设置默认值(勾选) } });