mcya / JavaScriptExperience

👮 JavaScript Experience for web(JavaScript归类:简单入门+数组+经典循环+字符串+函数+Date日期+简单对象+BOM+DOM) +[ Issues(js实用技巧)]
29 stars 8 forks source link

总结一下对 CheckBox 的相关操作 #69

Open mcya opened 5 years ago

mcya commented 5 years ago

总结一下对 CheckBox 的相关操作

mcya commented 5 years ago

html

文字选框联动 - input的id值和label的for值相同

<input style="vertical-align:middle; margin-top:0;" type="checkbox" value='ABC' id='DICTID'  />
<label for='DICTID'>DICTNAME</label>

if (array && array.length>0) {
    for (var i = 0; i < array.length; i++) {
        $("#queryForm #lungangTableId #groupCheckBoxId").append('<input style="vertical-align:middle; margin-top:0;" type="checkbox" value='+array[i].DICTID+' id='+array[i].DICTID+' dictname='+array[i].DICTNAME+' /><label class="labels" for='+array[i].DICTID+'>'+array[i].DICTNAME+'</label>')
    }
}
<input style="vertical-align:middle; margin-top:0;" type="checkbox" value='+array[i].DICTID+' id='+array[i].DICTID+' dictname='+array[i].DICTNAME+' />
<label class="labels" for='+array[i].DICTID+'>'+array[i].DICTNAME+'</label>
mcya commented 5 years ago

CheckBox 自定义样式

input[type="checkbox"] + label::before {
    content: "\a0";
    display: inline-block;
    vertical-align: .2em;
    width: .8em;
    height: .8em;
    margin-right: .2em;
    border-radius: .2em;
    background-color: silver;
    text-indent: .15em;
    line-height: .65;
}
input[type="checkbox"]:checked + label::before {
    content: "\2713";
    background-color: yellowgreen;
}
input[type="checkbox"] {/*清空原先样式*/
    position: absolute;
  clip: rect(0, 0, 0, 0);
    display: inline-block;
}

input[type="checkbox"]:focus + label::before {
    box-shadow: 0 0 .1em .1em #58a;
}
input[type="checkbox"]:disabled + label::before { /*disabled*/
    background-color: gray;
    box-shadow: none;
    color: #555;
}
mcya commented 5 years ago

CheckBox 取值赋值

1、取值,取多个选中的值 / 单个取值直接 .val()

$("#groupCheckBoxId input:checkbox:checked").each(function(index, item) {})
$("#groupCheckBoxId input:checkbox:checked").each(function(index, item) {
    checkboxArr.push({
        projid: projId,
        groupname: abcArr[''+index+''],
        dictname: $(this).attr("dictname"),
        type: "Y",
        agentid: $(this).val()
    })
})

2、赋值

// 设置checkbox为选中状态;
$('input:checkbox').attr("checked", 'checked');
// or
$('input:checkbox').attr("checked", true);
// 设置checkbox为不选中状态
$('input:checkbox').attr("checked", '');
// or
$('input:checkbox').attr("checked", false);
// 设置checkbox为禁用状态
$("input[type='checkbox']").attr("disabled", "disabled")
$("input[type='checkbox']").attr("disabled", true)

$("input[type='checkbox']").attr("disabled", "")
$("input[type='checkbox']").attr("disabled", false)