【问题标题】:Combining modal popup and HTML5 form validation结合模态弹出和 HTML5 表单验证
【发布时间】:2015-10-17 03:37:26
【问题描述】:

我有一个在模态弹出窗口中进行处理的表单。单击表单的按钮时,我希望发生以下情况:

  • 如果表单上的某个字段验证失败,则使用浏览器的本机显示屏显示验证失败。
  • 如果表单通过验证,则处理模式弹出窗口

但是我不能让它在 IE10 中工作。问题的症结在于:

  • 如果我使用 <button type="button" 的按钮(如 Bootstrap 模态弹出教程所建议的那样),则没有浏览器会执行其原生表单验证
  • 如果我使用<button type="submit" 的按钮,那么所有浏览器都会显示本机表单验证,但是如果验证通过,IE10 会继续重新加载页面(因为它提交表单),中止模式弹出窗口。 Chrome 未提交表单并正确显示模式弹出窗口。

我的问题是:如何在 IE10 中获得我想要的行为?


我的代码基于this tutorial基于触发按钮的不同模式内容部分。这是表格:

<p><form role="form" class="form-inline">
    <div class="form-group">
        <label class="control-label" for="input_opt_name">Name:</label>
        <input type="text" class="form-control" required id="input_opt_name" placeholder="Name Here" data-toggle="tooltip" title="Enter the name:">
    </div>
    <button type="button" class="btn btn-info" data-toggle="modal" data-target="#modal_window" data-req="blabla">Set Name</button>
</form></p>

该代码成功触发了验证弹出窗口;但是,在验证失败的情况下,无论如何都会显示模式弹出窗口。我添加了以下代码来抑制它,它有效:

$('#modal_window').on('show.bs.modal', function(e)
{
    var button = $(e.relatedTarget);

    if ( button[0].type == "submit" )
    {
        var tf = button.closest('form');
        if ( tf != undefined )
        {
            if ( !tf[0].checkValidity() )
                e.preventDefault();
        }
    }
}

【问题讨论】:

  • 我无法制作 jsfiddle 演示:jsfiddle 会抑制表单提交,因此会导致问题

标签: javascript html twitter-bootstrap internet-explorer-10


【解决方案1】:

我不明白为什么 Chrome 会抑制表单提交,而 IE10 不会。但是我找到了一种解决方法(受this question 启发)。

添加以下jquery:

$('form').bind("submit", function() { return false; });

这会导致表单提交被抑制,而不会干扰模式弹出窗口。这修复了 IE10,不会影响 Chrome。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    • 2016-05-20
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    相关资源
    最近更新 更多