0

$(".btn2").click(function() {
  alert("Form submitted successfully!")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form class="form">
  <h2>Sign up</h1>
    <br>
    <input type="text" name="username" id="username" placeholder="Enter name" required>
    <br>
    <br>
    <input type="password" name="password" id="password" placeholder="Enter password" required>
    <br>
    <br>
    <input type="email" name="email" id="email" placeholder="Enter email" required>
    <br>
    <br>
    <label for="gender">Gender:</label>
    <input type="radio" name="gender" id="male" value="Male">
    <label for="male">Male</label>

    <input type="radio" name="gender" id="female" value="Female">
    <label for="female">Female</label>
    <br>
    <br>
    <label for="dob">Date of birth:</label> <br>
    <input type="date" name="dob" id="dob" required>
    <br>
    <br>
    <button class="btn2" type="submit">Submit</button>
</form>
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 2
    What is `$(".btn2")`, is it of type "button" or type "submit"? If it's of type submit and contained within the form, it's going to submit the form without executing the script. You need to add more information to this post, such as your Html. Also, you should consider using `.on` instead of `.click` for your button. And no, I don't believe there is a built in function called `isValid`, you can use the jQuery plugin for form validation but it works differently than what you provided, read more here: [jqueryvalidation](https://jqueryvalidation.org/documentation/) – Ryan Wilson Oct 31 '22 at 13:28
  • 1
    Validation of an input field could be different based on the type of value it expects, for instance, it could be an email validation, a numeric validation, etc. – Ryan Wilson Oct 31 '22 at 13:35
  • 2
    Protip: Don't use line breaks for layout spacing. That's not their purpose. Use margin or padding. – isherwood Oct 31 '22 at 14:21

1 Answers1

0

Well, yes. You have an event handler attached to a button.

When the button is clicked the event handler will fires, and alert will be displayed. Due to the way alert works, this will block everything until the user clicks the button on the alert dialog. Then the JS will have finished and the button's default behaviour will occur, which triggers the form submission.

Part of submission is to run the native validation process.

If you want to display the alert only after that finishes, then you will need to:

  1. prevent the default behaviour of the button
  2. run the validation functions manually
  3. display the alert
  4. trigger form submission manually
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335