preventDefault without removing html5 validation

时间:2016-05-11 11:29:43

标签: javascript jquery html 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 () {

    });


    }
});

2 个答案:

答案 0 :(得分:7)

在您点击处理程序之上,您只需检查表单是否有效:

// 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-

答案 1 :(得分:1)

试试这个:

$( 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();
  });
});

并更改插入按钮类型以提交:

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