【问题标题】:Where should submit buttons be located for a form located in a Bootstrap modal?对于位于 Bootstrap 模式中的表单,提交按钮应位于何处?
【发布时间】:2021-05-04 22:24:29
【问题描述】:

下面是直接来自the docs 的示例HTML,除了我在表单元素中添加了id。为什么他们在表单之外显示按钮?它们不应该位于表单中,以便在单击时提交表单吗?请在底部查看我的典型 JavaScript。如果没有,是否需要将事件附加到button.btn-primary,然后将其提交表单,或者甚至不使用此事件并仅在单击主按钮事件中完成工作?

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">New message</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="my-form">
          <div class="mb-3">
            <label for="recipient-name" class="col-form-label">Recipient:</label>
            <input type="text" class="form-control" id="recipient-name">
          </div>
          <div class="mb-3">
            <label for="message-text" class="col-form-label">Message:</label>
            <textarea class="form-control" id="message-text"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Send message</button>
      </div>
    </div>
  </div>
</div>

我的典型 JS 应该是这样的:

const form = document.getElementById( "my-form" );
form.addEventListener( "submit", function ( event ) {
    event.preventDefault();
    // Make a XMLHttpRequest as necessary
} );

【问题讨论】:

    标签: javascript forms twitter-bootstrap bootstrap-modal


    【解决方案1】:

    button 元素有一个可选的form attribute,用于将其与form 相关联。这允许将button 定位在任何位置,而不必位于form 元素内。在可能需要不同提交参数的情况下,它还允许多个 button 元素与单个 form 相关联。

    【讨论】:

    • 谢谢斯科特。这样做似乎更合适。我的按钮现在看起来像&lt;button type="button" class="btn btn-primary" form="my-form"&gt;Save Project&lt;/button&gt;,但它没有触发表单的提交事件。我做错了什么?
    • 没关系。测试时,表单为空:) 再次感谢!编辑实际上,也许还没有走出困境......
    • @user1032531 确保在form 属性中使用formid
    • 再次感谢斯科特。我已经这样做了。将按钮 HTML 从 type="button" 更改为 type="submit" 并认为一切都很好。
    猜你喜欢
    • 2012-08-05
    • 2021-11-03
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多