I need to count :checked
checkboxes on popover content on bootstrap 3.
The problem is when I change checkboxes and close popover it doesn't saved. I tried to reinstall/destroy popovers and change dynamically content
option, but no results.
I also tried to create empty array and count checked checkboxes by hands, push
every new check to array, but no result again and it is very hard way.
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;
}
When you create the popover, you duplicate the content of your .filters
div, meaning that you have it twice. One that's hidden because it's in the .filters
div that's hidden because of
.filters {
display: none;
}
and one that's visible in your popover.
When you're counting, you're actually counting the checked boxes that are invisible and not those in the popover. The popover gets created outside of the .item
div and thus does not match the .item input[type=checkbox]:checked
selector. Changing it to .popover input[type=checkbox]:checked
would maybe do what you want.
Update
I've done a bit of research and found out that this usecase was not thougth about by the creators. So doing it is really tricky. But I've managed to find a solution for you:
$(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);
});
});