使用重定向到另一个内部 url JQuery 的表单身份验证

问题描述

我有这个代码,我需要验证身份验证,并在我单击名为“go there”的按钮时将表单重定向到另一个内部 URL。 在我的代码中,我需要提交部分。我可以寻求帮助吗?

jQuery(document).ready(function(e) {

    $('#btn-login').click(function(){ 
    var errorCount = 0; 
    $('#login-wrap input').each(function(){
      if($(this).val() === '') {
        var errorMsg = 'Please fill '+ $(this).prev('label').text();
        $(this).next('.errorMessage').text(errorMsg);
        errorCount += 1;
      }
    });

    if (errorCount === 0) { 
      $('#myModal').modal('show');  
    }
    return false;
  });
  
  // Open new tab on click
  $('#btn-gothere').click(function(){
    $('#myModal').modal('hide');  
    window.open($(this).data('url'));
  });
  
});

解决方法

您可以在 <form> 上设置侦听器以查找提交事件。
如果它被触发,则阻止它提交,验证您的输入,如果它们有效,请手动提交此表单。

当然,您不必查看 <form> 上的表单提交事件。您仍然可以使用您的 click 事件,但您必须为提交方法提供 form

// listen on form submit
$('#form').on('submit',event => {
  // prevent form from submitting
  event.preventDefault();
  
  // save target to variable (target is our form)
  const form = event.target;
  
  // check if form is valid
  if(isFormValid()) {
    // if form is valid then submit it and user will be moved to location provided in "action" parameter with all data from this form
    form.submit();
  }
});

// yes it is
const isFormValid = () => true;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" action="/some/url" method="POST">
  <button type="submit">Submit</button>
</form>