javascripthtmlformsbootstrap-modalrequired-field

Form inputs in modal not showing as required


I've read through some related articles without any luck of solving my own issue of getting form fields to appear as required. Perhaps the problem lies outside but I wanted to share in case it highlights a unique case.

This is a class assignment viewable in entirety here, it allows the user to add new trains to a schedule and update a Firebase DB. For this I used Bootstrap for the styles and also a modal pop-up that contains the form to create the new train. Everything works well, except that I cannot make the input fields required or prevent the 'submit' button.

I've tried wrapping all the fields (within their individual divs) in a element, as well as wrapping them each in a (as was recommended in another post) like so:

<div class="modal-body">
  <div class="panel panel-info">
    <div class="panel-body">
      <div class="form-group">
        <form>
          <label for="train_name">Train Name:</label> <input class="form-control" id="train_name" required="" type="text">
        </form>
      </div>
      <div class="form-group">
        <form>
          <label for="origin">Origin:</label> <input class="form-control" id="origin" required="" type="text">
        </form>
      </div>
      <div class="form-group">
        <form>
          <label for="destination">Destination:</label> <input class="form-control" id="destination" required="" type="text">
        </form>
      </div>
    </div>
  </div>
<div class="modal-footer">
  <button class="btn btn-primary" id="submit" type="submit" value="submit">Submit</button>
</div>
</div>

I double-checked the Doctype for HTML5 issues, but it checks out. Is my structure just wack?


Solution

  • Two things.

    1. The required attribute is only triggered when using the submit event listener. It looks like you are currently using click.

    2. You are wrapping each input in it's own form tag. You should have a single form tag wrapping all of your inputs

    Example:

    <div class="panel-body">
      <form id="my-form">
        <div class="form-group">
         <label for="train_name">Train Name:</label> <input class="form-control" id="train_name" required="" type="text">
        </div>
        <div class="form-group">
          <label for="origin">Origin:</label> <input class="form-control" id="origin" required="" type="text">
        </div>
        <div class="form-group">
          <label for="destination">Destination:</label> <input class="form-control" id="destination" required="" type="text">
        </div>
        <button class="btn btn-primary" id="submit" type="submit">Submit</button>
      </form>
    </div>
    
    
    $("#my-form").on("submit", function (e) {
      //do your form submission logic here
    })