Peter Pik Peter Pik - 2 months ago 7
HTML Question

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 () {

});


}
});

Answer

try this:

$( document ).ready(function() {
  $("#insert").click(function(e) {
    if($('#description').val() != "" && $('#title').val() != "" && $('#description').val().length >= 5) {
      div_hide();
      $.post("insert.php",
      {
         title:  $('#title').val(),
         body: $('#description').val(),
         longitude: currentMarker.lng(),
         latitude: currentMarker.lat()
      },
      function (data) { //success callback function
    }).error(function () {
    });
    }
  });

  $("form").submit(function(e){
     e.preventDefault();
  });
});

and change insert button type to submit:

<input type="submit" id="insert" value="Tilføj"></span>