1

Below is example HTML straight from the docs except that I added an id to the form element. Why are they showing the buttons outside of the form? Shouldn't they be located within the form so that when clicked, the form is submitted? Please see my typical JavaScript at the bottom. If not, is it required to attach an event to the button.btn-primary which will then submit the form, or not even use this event and just do the work within the click primary button event?

<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>

My typical JS would be something like the following:

const form = document.getElementById( "my-form" );
form.addEventListener( "submit", function ( event ) {
    event.preventDefault();
    // Make a XMLHttpRequest as necessary
} );
user1032531
  • 24,767
  • 68
  • 217
  • 387

1 Answers1

1

The button element has an optional form attribute that is used to associate it with a form. This allows the button to be positioned anywhere, not necessarily inside of the form element. It also allows for multiple button elements to be associated with a single form in cases where different submit parameters might be needed.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Thanks Scott. Doing this way seems much more appropriate. My button now looks like ``, but it is not triggering the submit event of the form. What am I doing wrong? – user1032531 Jan 31 '21 at 15:46
  • Nevermind. When testing, the form was empty :) Thanks again! EDIT Actually, maybe not out of the woods yet... – user1032531 Jan 31 '21 at 15:49
  • @user1032531 Make sure to use the `id` of the `form` in the `form` attribute. – Scott Marcus Jan 31 '21 at 15:55
  • Thanks again Scott. I had already been doing so. Changed the button HTML from `type="button"` to `type="submit"` and think all is good. – user1032531 Jan 31 '21 at 16:03