Search code examples
javascriptjqueryhtmltwitter-bootstrapbootstrap-accordion

Remove bootstrap accordion panel (Jquery)


I have a bootstrap accordion whose panels are generated according the input in an input type=number. The problem is that when I want to delete, it removes a panel. I have only been able to remove the internal div, but the panel-heading still appears in the accordion.

This is the HTML for accordion:

<div class="panel-group" id="accordion">

    </div>
</div>

and the template:

<div class="panel panel-default" id="template_shovel">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapse1">
                    Shovel 01
                </a>
            </h4>
        </div>
        <div id="collapse1" class="panel-collapse collapse in">
            <div class="panel-body">
Some more HTML
</div>

    </div>
    </div>

The JavaScript:

var hash = 1;
$(function () {
    $(':input').bind('keyup mouseup', function () {
        var $templateShovel = $('#template_shovel');

        if (this.id == 'nshovels') {
            var value = $(this).val();
            if (value == hash) {
                var $newPanel = $templateShovel.clone();
                $newPanel.find(".collapse").removeClass("in");
                $newPanel.find(".accordion-toggle").attr("href", "#collapseShovel" + (hash))
                         .text("Shovel - n #" + hash);
                $newPanel.find(".panel-collapse").attr("id", "collapseShovel" + hash).addClass("collapse").removeClass("in");
                $('#accordion').append($newPanel.fadeIn());
                hash++;
            }
            else if (value < hash) {
                var idPanel = '#collapseShovel' + (hash - 1).toString();
                $('#accordion').find(idPanel).closest('div').andSelf().remove();

                hash--;
            }
        }
    });
});

nshovels is the input's id that has to add or delete panels.


Solution

  • If I'm understanding correctly, you are trying to delete both the div.panel-heading AND div.panel-collapse, but keep the div.panel. To this can use .empty() after targeting the panel. This will remove all child elements, but keep the div.panel itself.

    var idPanel = '#collapseShovel' + (hash - 1).toString();
    $('#accordion').find(idPanel).closest('.panel').empty();
    

    Otherwise if you're trying to remove the actual div.panel item that contains the div.panel-heading and div.panel-collapse:

    var idPanel = '#collapseShovel' + (hash - 1).toString();
    $('#accordion').find(idPanel).closest('.panel').remove();
    

    Here is a jsfiddle demonstrating the basic remove() vs empty() functionality for an collapse panel accordion as well as input:number blur example:

    Hopefully this helps!