Search code examples
javascripthtmljqueryrequired

avoid refresh page and required field doesn't work


I want to submit a form disabling refresh and I want the ajax to do the POST request to avoid refreshing the page.

Here I got something structure like this but my required tag doesn't work

<form id="test">
     <input type="text" name="title" required/>
</form>

<button id="submitForm">Save</button>

Then I make javascript like this:

$('#submitForm').click(function(e){
     e.preventDefault();
     $("#test").submit();
     console.log('success');
});

why is my form refreshing and not validating the required field?


Solution

  • You are bypassing all stuff you get for free.

    Here is how

    1. Use the submit event
    2. Move the submit button to the form

    $('#test').on("submit", function(e) {
      e.preventDefault();
      // $.post(url.....)
      console.log('success');
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form id="test">
      <input type="text" name="title" required/>
      <button type="submit">Save</button>
    </form>

    1. or use form="test" on the tag

    $('#test').on("submit", function(e) {
      e.preventDefault();
      // $.post(url.....)
      console.log('success');
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form id="test">
      <input type="text" name="title" required/>
    </form>
    <button type="submit" form="test">Save</button>

    If you are planning to add the form dynamically, you need to delegate

    $("#container").on("submit", ".dynForm", function(e) {
      e.preventDefault();
      // $.post(url.....)
      console.log('success', this.id);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="container">
      <form id="test1" class="dynForm">
        <input type="text" name="title" required/>
      </form>
      <form id="test2" class="dynForm">
        <input type="text" name="title" required/>
      </form>
      <form id="test3" class="dynForm">
        <input type="text" name="title" required/>
      </form>
    </div>
    
    
    <button type="submit" form="test1">Save 1</button>
    <button type="submit" form="test2">Save 2</button>
    <button type="submit" form="test3">Save 3</button>