【发布时间】:2015-10-03 15:51:32
【问题描述】:
我想将选中复选框的值设置为文本输入
例如:看这张图片Click
问题是当我单击“全选”复选框时,“子”复选框被选中,但文本框中未设置值,当我取消选中“全选”复选框时设置了值
我想在数组中获取复选框值,所以我使用 map 函数,
请在 fiddle 上查看 jquery
HTML 代码
<form action="" id="form">
<input type="checkbox" id="selectAll">
<label for="selectAll">Select All</label><br>
<div class="child">
<input type="checkbox" class="selectCb" value="1" id="one">
<label for="one">One</label><br>
<input type="checkbox" id="two" class="selectCb" value="2">
<label for="two">Two</label><br>
<input type="checkbox" class="selectCb" value="3" id="three">
<label for="three">Three</label><br>
</div>
<input type="text" id="textBox">
</form>
编辑
两个代码都有效
$(document).on("click", "#selectAll", function () {
var chkAll = $(".child input[type='checkbox']:checked").map(function() {
return $(this).val();
}).get();
$("#textBox").val(chkAll.join(' '));
});
检查小提琴fiddle 2
$(document).on("change", "#selectAll", function () {
var chkAll = $(".child input[type='checkbox']").prop('checked', this.checked).map(function () {
return $(this).val();
}).get();
$("#textBox").val(chkAll.join(' '));
});
检查小提琴fiddle 3
现在我怀疑哪个更好更正确?
因为我想为所有复选框设置背景图像,所以我使用 css 隐藏所有复选框
#form input[type="checkbox"] {
display: none;
}
并使用以下 css 代码为复选框设置背景图像
为“全选”复选框设置背景
input[type="checkbox"]#selectAll + label#selectAllLbl::before {
content: '';
background: url('http://s30.postimg.org/uhql9zd5p/chk_uncheck.png') no-repeat;
height: 22px;
width: 22px;
display: inline-block;
margin-right: 10px;
}
input[type="checkbox"]#selectAll:checked + label#selectAllLbl::before {
content: '';
background: url('http://s9.postimg.org/6k81psojf/chk_enabled.png') no-repeat;
}
为“子”复选框设置背景
input[type="checkbox"].selectCb + label.childLbl::before {
content: '';
background: url('http://s30.postimg.org/uhql9zd5p/chk_uncheck.png') no-repeat;
height: 22px;
width: 22px;
display: inline-block;
margin-right: 10px;
}
input[type="checkbox"].selectCb:checked + label.childLbl::before {
content: '';
background: url('http://s9.postimg.org/6k81psojf/chk_enabled.png') no-repeat;
}
是吗?在 jquery 中使用隐藏的复选框 id 和类
<input type="checkbox" id="selectAll">
<input type="checkbox" class="selectCb" value="1" id="one">
【问题讨论】:
标签: javascript jquery html checkbox