Why does HTML's "required" attribute work with input type="submit" but not with button?

87 Views Asked by At
<form action="#" method="get" id="bookForm">
        <div class="field">
          <label for="title">Title</label>
          <input type="text" id="title" maxlength="20" required/>
        </div>
        <div class="field">
          <label for="author">Author</label>
          <input type="text" id="author" maxlength="15" required/>
        </div>
        <div class="field">
          <label for="year">Year</label>
          <input type="text" id="year" maxlength="4"/>
        </div>
        <div class="field">
          <label for="read">Read</label>
          <input type="checkbox" id="read" class="button"/>
        </div>
        <div id="form-buttons" class="field">
          <button id="add-book-btn" type="submit" class="button">
            <!-- <input type="submit" value="add"> -->
            Add book
          </button>
          <button id="reset-modal-btn" class="button">
            Reset
          </button>
       </div>
  </form>

I have the above form. The first two inputs are required, however it's still possible to submit the form. The attribute only works when input type='submit' is used.

If it helps, I should mention that I have an event handler on the button. It takes the data in the inputs and creates an object. Also, I'm using webpack to bundle different javascript modules.

Try adding type="submit" attribute to button. Added method="get" attribute to form. Rename form's action attribute. Used input type="submit"

1

There are 1 best solutions below

0
D B On

Removing e.preventDefault() from the event handler's callback function fixes the issue.