2016-07-27 108 views
0

HTML標記;Materialisecss jQuery驗證不起作用

<div id="address" class="col s12"> 
    <div class="row"> 
     <form method="post" action="" id="addressDetails"> 
      <div class="input-field col s6"> 
       <textarea id="lAddress" name = 'lAddress' minlength='20' maxlength='100' class="materialize-textarea" class="validate" required length="100"></textarea> 
       <label for="lAddress" data-error="Must be between 20 to 100 Characters">Local Address</label> 
      </div> 
      <div class="input-field col s6"> 
       <textarea id="pAddress" name = 'pAddress' minlength='20' maxlength='100' class="materialize-textarea" class="validate" required length="100"></textarea> 
       <label for="pAddress" data-error="Must be between 20 to 100 Characters">Permanent Address</label> 
      </div> 
     </form> 
    </div> 
    <div class="row center-align"> 
     <button type="submit" name="submitAddress" form="addressDetails" class="waves-effect waves-light light-blue darken-1 btn updateProfile">Save Address Details</button> 
    </div> 
</div> 

JavaScript代碼:

function updateProfile(event) { 
    console.log(this); 
    event.preventDefault(); 
    form = $(this).closest('.col.s12').find('form'); 
    $.ajax('profile/updateProfile.php', { 
     type: "POST", 
     dataType: "json", 
     data: form.serialize(), 
     success: function(result) { 
      Materialize.toast(result.message, 4000); 
     }, 
     error: function() { 
      Materialize.toast("Failed: Please contact admin.", 4000); 
     }, 
     timeout: 5000 
    }); 
} 

$(document).ready(function() { 
    $("button.updateProfile").on('click', updateProfile); 
}); 

早些時候與正常的表單提交驗證是工作。但現在有了jQuery AJAX請求,我可以發送數據,但當表單無效時,它顯示紅色錯誤,但它接受錯誤的表單。

當我使用$("button.updateProfile").on('sumbit', updateProfile);它正在驗證,但它正在重新加載頁面,preventDefault不起作用。

回答

2

$("button.updateProfile").on('click', updateProfile);

這不會與物質化驗證的幫助下進行驗證。你必須尋找submit

再次提交它會有問題,它不是在尋找提交形式。

$("button.updateProfile").on('sumbit', updateProfile);

取而代之的按鈕使用形式,然後將查找表單提交。像這樣

$("form").on('submit', updateProfile);

這將很好地工作。

因此,請記住,只要您提交表單提交表單,而不是提交按鈕。