2016-07-27 152 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);

这将很好地工作。

因此,请记住,只要您提交表单提交表单,而不是提交按钮。