Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preventDefault without removing html5 validation

I've created following form with standard html validation. for this form i want to avoid the refresh of page when i press submit button. Therefor in my jquery code i've added preventDefault(). which work by not refreshing the page, however it also remove the html5 validation? how can i apply both things?

form

<form method="post" action="">

    <div class="reg_section personal_info">
        <input type="text" name="username" id="title" value="" placeholder="title" required="required" maxlength="25">
        <textarea name="textarea" id="description" value="" placeholder="Beskrivelse" required="required" minlength="100"></textarea>
        </div>


    <div>
          <span class="submit" style="text-align: left; padding: 0 10px;"><input type="submit" id="insert" value="Tilføj"></span>
          <span class="submit" style="text-align: right; padding: 0 10px;"><input TYPE="button" value="Fortryd" onclick="div_hide();"></span>
    </div>

</form>

jquery

  $("#insert").click(function(e) {
    e.preventDefault(); // prevent default form submit


    if(!$('#description').val() == "" && !$('#title').val() == "" && $('#description').val().length >= 100) {



      div_hide();

      $.post("insert.php",
      {
         title:  $('#title').val(),
         body: $('#description').val(),
         longitude: currentMarker.lng(),
         latitude: currentMarker.lat()
      },
      function (data) { //success callback function



    }).error(function () {

    });


    }
});
like image 326
Peter Pik Avatar asked May 11 '16 11:05

Peter Pik


1 Answers

On top of you click handler, you could just check if form is valid:

// prevent default form submit if valid, otherwise, not prevent default behaviour so the HTML5 validation behaviour can take place

if($(this).closest('form')[0].checkValidity()){
    e.preventDefault();
}

-jsFiddle-

like image 88
A. Wolff Avatar answered Oct 23 '22 06:10

A. Wolff