我需要计算 Bootstrap 3 上弹出窗口内容上的 :checked
复选框数量。
问题是当我更改复选框并关闭弹出窗口时,它不会保存。我尝试重新安装/销毁弹出窗口并动态更改 content
选项,但没有结果。
我还尝试创建空数组并手动计算选中的复选框,将每个新检查推送
到数组,但再次没有结果,这是非常困难的方法。
js:
$(function () {
$('.item').popover({
placement: 'bottom',
html: true,
content: function () {
return $(this).find('.filters').html();
}
});
$('#count').click(function() {
var filter = $('.item input[type=checkbox]:checked').map(function () {
return this.value;
}).get();
$('#res').text(filter);
});
});
html:
<div class="item">
<a href="#" onclick="return false;" class="btn btn-primary">click for popover</a>
<div class="filters">
<ul class="list-unstyled">
<li>
<input type="checkbox" value="1" checked="checked" id="filter1">
<label for="filter1">Filter 1</label>
</li>
<li>
<input type="checkbox" value="2" checked="checked" id="filter2">
<label for="filter2">Filter 2</label>
</li>
<li>
<input type="checkbox" value="3" id="filter3">
<label for="filter2">Filter 3</label>
</li>
</ul>
</div>
</div>
<br>
<a href="#" onclick="return false;" id="count">count</a>
<div id="res"></div>
CSS:
.filters {
display: none;
}
.popover-content {
width: 100px;
}
最佳答案
当您创建弹出窗口时,您会复制 .filters
div 的内容,这意味着您拥有它两次。一个被隐藏的,因为它位于 .filters
div 中,而隐藏的原因是
.filters {
显示:无;
}
以及在弹出窗口中可见的一个。
当您计数时,您实际上是在计算不可见的复选框,而不是弹出窗口中的复选框。弹出窗口是在 .item
div 外部创建的,因此与 .item input[type=checkbox]:checked
选择器不匹配。将其更改为 .popover input[type=checkbox]:checked
可能会达到您想要的效果。
更新
我做了一些研究,发现创建者没有考虑到这个用例。所以做起来真的很棘手。但我已经设法为您找到解决方案:
$(function () {
$('.item').popover({
placement: 'bottom',
html: true,
content: function () {
return $(this).find('.filters').html();
}
});
//Magic
$(".item").on("shown.bs.popover",function(){
$(".popover-content input").on("change",function(){
if(this.checked){
this.setAttribute("checked","checked");
}else{
this.removeAttribute("checked");
}
$(".filters").html($(".popover-content").html());
});
});
$('#count').click(function() {
var filter = $('.item input[type=checkbox]:checked').map(function () {
return this.value;
}).get();
$('#res').text(filter);
});
});
关于javascript - Bootstrap 弹出窗口不保存复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25196155/