本文目錄一覽:
如何用js 給checkbox
思路:獲取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;iboxes.length;i++){
for(j=0;jval.length;j++){
if(boxes[i].value == val[j]){
boxes[i].checked = true;
break
}
}
}
}
3、效果演示
js如何實現複選框的多級聯動
1、為 複選框的 onclick 事件 綁定js 方法
2、在 js 方法中,判斷複選框當前值
2.1、如果選中,將關聯的複選框也選中
2.2、如果沒有選中,將關聯的複選框取消選中
js中怎麼獲取checkbox選中的值
js中獲取checkbox選中的值的方法:
script
function checkbox()
{
var str=document.getElementsByName(“box”);
var objarray=str.length;
var chestr=””;
for (i=0;iobjarray;i++)
{
if(str[i].checked == true)
{
chestr+=str[i].value+”,”;
}
}
if(chestr == “”)
{
alert(“請先選擇一個愛好”);
}
else
{
alert(“先擇的是:”+chestr);
}
}
/script
選擇愛好:
input type=”checkbox” name=”box” id=”box1″ value=”跳水” /跳水
input type=”checkbox” name=”box” id=”box2″ value=”跑步” /跑步
input type=”checkbox” name=”box” id=”box3″ value=”聽音樂” /聽音樂
input type=”button” name=”button” id=”button” onclick=”checkbox()” value=”提交” /
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/190824.html