2017-09-09 24 views
0

当按钮位于<form></form>标记之外时,我似乎无法使我的表单得到验证。任何想法我可以如何实现这一目标?由于技术原因,我无法将其放置在表单中(它位于粘滞的导航栏内)。当按钮位于表单标记之外时,jQuery表单无法验证

我的HTML标记:

<form id="frm-shipping" class="frm-shipping" method="post"> 

    <input type="text" name="contact_phone" class="has_validation" 
    placeholder="Contact phone" value="" data-validation="required" 
    data-validation-error-msg="this field is mandatory!" > 

    <input type="text" name="first_name" class="has_validation" 
    placeholder="First Name" value="" data-validation="required" 
    data-validation-error-msg="this field is mandatory!" > 

</form> 

<button class="btn" onclick="nextStep();">Next</button> 

而jQuery代码:

function nextStep() 
{ 

    $.validate({  
     form : '#frm-shipping',  
     borderColorOnError:"#FF0000", 
     onError : function() {  
     },  
     onSuccess : function() { 

      var params = $("#frm-shipping").serialize(); 
      // AJAX call here 

     } 
    }); 
} 

当我按一下按钮,没有任何反应。根本不算什么:(任何建议?

+0

我建议使用onsubmit之前,但赢了没有工作。正如@BenM所说 - 代码看起来很好,因为在这个实现中“没有任何事情发生”是一个有效的结果。 –

+0

因为除了序列化表单之外,你没有做任何事情。 – BenM

+0

我删除了做某件事的部分,因为它无关紧要。当我把按钮放在窗体中时,它就可以工作。当我将它移到外面时,它不会。 – user1996496

回答

1

您可将按钮分配与form属性的形式。见W3Schools example

<button class="btn" form="frm-shipping" onclick="nextStep();">Next</button> 

function nextStep() 
 
{ 
 
    $.validate({  
 
     form : '#frm-shipping',  
 
     borderColorOnError:"#FF0000", 
 
     onError : function() { 
 
      console.log('error') 
 
     },  
 
     onSuccess : function() { 
 
      console.log('te3st') 
 
      var params = $("#frm-shipping").serialize(); 
 
      // AJAX call here 
 

 
     } 
 
    }); 
 
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script> 
 
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script> 
 

 

 

 
<form id="frm-shipping" class="frm-shipping" method="post"> 
 

 
    
 
    <input type="text" name="contact_phone" class="has_validation" 
 
    placeholder="Contact phone" value="" data-validation="required" 
 
    data-validation-error-msg="this field is mandatory!" > 
 

 
    <input type="text" name="first_name" class="has_validation" 
 
    placeholder="First Name" value="" data-validation="required" 
 
    data-validation-error-msg="this field is mandatory!" > 
 

 
    
 
    
 
</form> 
 

 
<button class="btn" form='frm-shipping' onclick="nextStep();">Next</button>

1

试试这个

$('.btn').click(function(){ 
     Validate method 
    });