当按钮位于表单标记之外时,jQuery表单不会验证

时间:2017-09-09 08:29:20

标签: javascript jquery validation

当按钮位于<form></form>标记之外时,我似乎无法让我的表单验证。我有什么想法可以达到这个目的吗?由于技术原因,我无法将其放在表单中(它位于粘性导航栏内)。

我的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

        }  
    });
}

当我点击按钮时,没有任何反应。什么都没有:(有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您可以将按钮分配给具有form属性的表单。请参阅W3Schools example

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

&#13;
&#13;
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

        }  
    });
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

试试这个

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