Bootstrap popover不保存复选框

时间:2014-08-08 04:40:00

标签: javascript jquery twitter-bootstrap twitter-bootstrap-3 popover

我需要在bootstrap 3上的弹出窗口内容上计算:checked个复选框。

问题是,当我更改复选框并关闭弹出窗口时,它不会保存。我尝试重新安装/销毁弹出框并动态更改content选项,但没有结果。

我还尝试用手创建空数组和计数复选框,push每次检查新数组,但没有结果,这是非常困难的。

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;
}

更新:http://jsfiddle.net/sirjay/0vetvfpz/

1 个答案:

答案 0 :(得分:5)

创建弹出框时,您复制了.filters div的内容,这意味着您有两次。一个被隐藏的,因为它隐藏在.filters div中,因为它被隐藏了 .filters { display: none; }

和你的popover中可见的一个。

当你计算时,你实际上是在计算不可见的复选框而不是弹出框中的复选框。弹出窗口是在.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);
    });
});