为什么Bootstrap数据解散和模态('隐藏')不起作用?

时间:2018-01-23 21:51:32

标签: jquery asp.net-mvc twitter-bootstrap

首先,如果文本框中没有值,我想隐藏模态。其次,data-dismiss无效。我没有在代码中看到任何问题。任何猜测?请建议我。

/My form
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {   
       @Html.TextBoxFor(m => m.txtName)
       @Html.HiddenFor(m => m.hiddenNameId)
       @Html.ValidationMessageFor(m => m.txtName, "", new { @class = "error" })
       <button type="submit" id="submit" data-toggle="modal" data-target="#myModal">Produce Page</button>      
    } 

//My Modal

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModal" aria-hidden="true">
    ...
            <div class="modal-header">
                ...
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
  </div>

//Script

$(function () {
    $('#submit').click(function () {
        var value = $('#txtName').val(); 
        if (value) {
            $("#myModal").modal('show');
        }
        else {
            $("#myModal").modal('hide');
        }
    });
    });

1 个答案:

答案 0 :(得分:1)

你总是得到这个模型,因为你的按钮被连接起来使用标记来触发它,使用按钮标记中的data-toggledata-target属性。

删除它们,现在当用户点击按钮时它不会触发模态对话框。

<button type="submit" id="submit" >Produce Page</button>      

单击该按钮时,将执行您的javacsript代码(您连接的单击事件处理程序),它将根据txtName输入的值有条件地显示模式对话框。

此外,您可能不需要代码来隐藏它。因为当模态不存在时,使用会点击按钮(因此背景上的按钮是可点击的)。在这种情况下,您需要做的就是在if条件通过时显示模态对话框。

$(function () {
    $('#submit').click(function (e) {
        e.preventDefault();
        var value = $('#txtName').val();
        if (value) {
            $("#myModal").modal('show');
        }
    });
});

关于你没有关闭模态对话框的第二个问题,只要你有一个关闭按钮的正确标记(带有所需的属性),它就应该工作。 (在您的问题中,您没有发布完整标记)。这是working jsbin供您参考