您的位置:首页 > Web前端 > JavaScript

JS 怎么控制 checkbox 选中

2017-12-11 00:00 447 查看
<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、效果演示



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息