返回false不在jquery中的表单提交上工作

时间:2017-02-06 14:55:59

标签: javascript jquery html

function SaleProduct() {   
      var CusId=$('#CusId').val(); 
      $.get('customer-id.php?CusId='+CusId, function(data) {
         if(data==0){
		   alert("Customer Id not valid.")
		   return false;
		 }
        });
     }
<form action="sales-edit-insert.php" method="post" onSubmit="return SaleProduct()">
  <input type="text" name="CusId" id="CusId"/>
  <!--Some input field here-->
  <input type="submit" value="Submit"/>
</form>

返回false;或e.preventDefault();我提交表格时没有处理上述功能。表格在显示警告后提交。

2 个答案:

答案 0 :(得分:1)

您的SaleProduct不返回任何内容(实际上undefined) 您可以使用return false;属性中的onsubmit停止立即发送表单:

<form action="sales-edit-insert.php" method="post" onSubmit="SaleProduct(); return false;">

稍后您可以手动提交表单:

function SaleProduct() {   
  var form = ...;
  var CusId=$('#CusId').val(); 
  $.get('customer-id.php?CusId='+CusId, function(data) {
    if(data==0){
      alert("Customer Id not valid.")
      return;
    }
    form.submit();
  });
  return false; // you can also move this statement to here from attribute
}

获取表单元素的最简单方法是将其提供给onsubmit

<form action="sales-edit-insert.php" method="post" onSubmit="return checkCustomer(this)">

和js:

function checkCustomer(form) {
  //code from above
  return false;
}

答案 1 :(得分:0)

您已经使用了jQuery,为什么还要使用onsubmit属性。尝试

<form action="sales-edit-insert.php" method="post" id="sale-product-form">

jQuery(function($) {
  $('#sale-product-form').on('submit', function(e) {
    e.preventDefault()
    var form = this;
    $.get('customer-id.php', $(form).serialize(), function(data) {
      if (data == 0) {
        alert('Customer Id not valid.')
      } else {
        form.submit() // submit normally
      }
    })
  })
})
相关问题