使用jQuery显示/隐藏bootstrap手风琴面板

时间:2014-09-24 20:19:56

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

我有一个bootstrap手风琴。现在我想仅在某种情况下启用panel。当我的某个面板有效时,只有其他面板should be collapsible

<div class="panel-group" id="accordion">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">Collapsible Group
                    Item #1 </a>
            </h4>
        </div>
        <div id="collapseOne" class="panel-collapse collapse in">
            <form id="myform" action="" method="post"> //when this form is valid, then open the collapseTwo panel
            <div class="panel-body">
                <input type="text" id="txtName" name="txtName" />
                <br />
                <input type="text" id="txtCountry" name="txtCountry" />
                <br />
                <input id="btn" type="submit" name="submit" value="Submit" />
                <br />
            </div>
            </form>
        </div>
    </div>
    <div id="clickMe" class="panel panel-default"> // this will remain closed unless the above form is not valid
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">Collapsible Group
                    Item #2 </a>
            </h4>
        </div>
        <div id="collapseTwo" class="panel-collapse collapse">
            <div class="panel-body">
                //Some data
            </div>
        </div>
    </div>

</div>

<script type="text/javascript">
    $(document).ready(function () {

        $("#myform").validate({
            rules: {
                txtName: {
                    required: true
                },
                txtCountry: {
                    required: true
                }
            }
        });

        $("#myform").valid();

        $('#clickMe').on('shown.bs.collapse', function (e) {     //i click on the panel header

            if ($('#myform').valid()) {   //now if the first panel(which contains form) is valid
               $('#collapseTwo').collapse('show');    //then show the clicked panel
            }
            else {
                $('#collapseTwo').collapse('hide');  //else always keep it hidden/locked
                alert('form invalid');
            }
        })
    });
</script>

Fiddle

这与它实际应该如何运作的行为并不相符。

应该锁定collapseTwo面板,并显示一条警告消息,指出collapseOne面板是无效的。如果表单有效,那么它应该是折叠的默认行为。

2 个答案:

答案 0 :(得分:3)

显示面板后,您正在进行检查:

$('#clickMe').on('shown.bs.collapse', function (e) {

相反,请使用show方法:

$('#clickMe').on('show.bs.collapse', function (e) {

还有其他事情发生,但这是一个开始。


更新:发现另一个问题......无需强行崩溃行为。只是在必要时阻止它。

if (!$('#myform').valid()) {
    return false;
}

Demo

答案 1 :(得分:1)

使用默认折叠方法显示和隐藏

显示

$("#collapseOne").collapse('show');

隐藏

$("#collapseOne").collapse('hide');