简体   繁体   中英

Jquery check required field before submission

I have a form with a hyper link for submission. What I would like to achieve is that jquery could check all required fields then execute my logic. If any of the required fields is empty jquery should simply do what browser's default behavior does. But my implementation below is only able to pop up an alert window. Please help me improve.

if($("#required_field_1")[0].checkValidity() == false ||
   $("#required_filed_2")[0].checkValidity() == false) {
   alert("Please fill all required field");
}
else {
  $('#form_1').ajaxForm({
    delegation: true,
    beforeSend: myFunc1,
    success:    myFunc2,
    data:       {"op": op,
                 "payslip_date_start": $("#payslip_date_start").val(),
                 "payslip_date_end": $("payslip_date_end").val()}
  });
  $('#form_1').submit();
}

The only way to do that is by submitting the form, like this and be sure you added the required attribute

var $myForm = $('form#myForm')
if (!$myForm[0].checkValidity()) {
  // If the form is invalid, submit it. The form won't actually submit;
  // this will just cause the browser to display the native HTML5 error messages.
  $myForm.find(':submit').click()
}

You can found more here: https://stackoverflow.com/a/11867013/3914736

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