2017-09-09 22 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 
    });