<script>
window.onload = function(){
//获取id 为 check 的隐藏域的值(比如“2,5”)
//将name 为 about ,value为2和5的checkbox 设为选中
}
</script>
以上代码怎么写?
思路:获取checkbox对象,根据value属性设置checkbox的checked属性(true为选中,false为取消选中)。下面实例演示——根据文本框的制定值设置复选框的选中项:
1、HTML结构
1 2 3 4 5 6 | < input name = "test" type = "checkbox" value = "1" />item-1 < input name = "test" type = "checkbox" value = "2" />item-2 < input name = "test" type = "checkbox" value = "3" />item-3 < input name = "test" type = "checkbox" value = "4" />item-4 < input name = "test" type = "checkbox" value = "5" />item-5 < input type = "text" id = "val" >< input type = "button" value = "确定" onclick = "fun()" > |
2、javascript代码
1 2 3 4 5 6 7 8 9 10 11 12 | function fun(){ var val = document.getElementById( "val" ).value.split( "," ); var boxes = document.getElementsByName( "test" ); for (i=0;i<boxes.length;i++){ for (j=0;j<val.length;j++){ if (boxes[i].value == val[j]){ boxes[i].checked = true ; break } } } } |
3、效果演示
![5bafa40f4bfbfbedb576cc047ef0f736afc31f99.jpg](https://i-blog.csdnimg.cn/blog_migrate/d793e716732127065873550c913e8655.gif)