简体   繁体   中英

return false not working on form submit in jquery

 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> 

return false; or e.preventDefault(); not working on above function when I submit the form. Form is submitted after showing an alert.

Your SaleProduct returns nothing(actually undefined ).
You can stop immediate form sending with return false; inside of onsubmit attribute:

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

And later you can submit your form manually:

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
}

Most simple way to get form element is provide it into onsubmit :

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

And js:

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

You're using jQuery already so why bother with the onsubmit attribute. Try

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

and

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
      }
    })
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM