html form - `required` attribute not triggered with onclick confirm

I have a html form with input fields that require a value before submission and to achieve this I am using the required attribute in html5 Which is shown in the snippet below with the header Form One.

The problem is I'd like to add a confirm pop-up message after the delete button is clicked -- asking if the user wants to continue.

I have done this in the snippet shown below with the header Form Two but the problem is, the required attribute is not showing when the input field is empty and submitted.

The form gets submitted before the required method is triggered. Anyone has any ideas to solve this html5 incompetence?

THANKS

<h2>Form One </h2>

<form method="post" action="example.com" id="delete_page">

  Name : <input type="name" required><br>
  <input type="button" value="Cancel">
  <input type="submit" value="Delete">

</form>
<hr>
<h2>Form Two </h2>
<form method="post" action="example.com" id="delete_page">

  Name : <input type="name" required><br>
  <input type="button" value="Cancel">
  <input type="submit" onclick="confirm('Are you sure you want to submit')" value="Delete">

</form>

Answers:

Answer

Try using onsubmit on your <form> rather than the button.

<h2>Form Two </h2>
<form method="post" action="example.com" id="delete_page"
      onsubmit="return confirm('Are you sure you want to submit?')">

  Name : <input type="name" required><br>
  <input type="button" value="Cancel">
  <input type="submit" value="Delete">

</form>

Browser form validation only kicks in on a submit event.

This will also prevent your form from submitting if the user chooses to "Cancel" the popup.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.