如何用js讀取複選框的值?
阿新 • • 發佈:2018-12-11
思路:首先利用name屬性值獲取checkbox物件,然後迴圈判斷checked屬性:如果為true表示被選中,false則表示未選中。
1、HTML結構
<
input
type
=
"checkbox"
name
=
"test"
value
=
"1"
/><
span
>1</
span
>
<
input
type
=
"checkbox"
name
=
"test"
value
=
"2"
/><
span
>2</
span
>
<
input
type
=
"checkbox"
name
=
"test"
value
=
"3"
/><
span
>3</
span
>
<
input
type
=
"checkbox"
name
=
"test"
value
=
"4"
/><
span
>4</
span
>
<
input
type
=
"checkbox"
name
=
"test"
value
=
"5"
/><
span
>5</
span
>
<
input
type
=
'button'
value
=
'提交'
onclick
=
"fun()"
/>
2、javascript程式碼
function
fun(){
obj = document.getElementsByName(
"test"
);
check_val = [];
for
(k
in
obj){
if
(obj[k].checked)
check_val.push(obj[k].value);
}
alert(check_val);
}