Peter Pik
Peter Pik

Reputation: 11193

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

    });


    }
});

Upvotes: 10

Views: 5838

Answers (2)

A. Wolff
A. Wolff

Reputation: 74420

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-

Upvotes: 12

Dhara Parmar
Dhara Parmar

Reputation: 8101

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>

Upvotes: 1

Related Questions