1

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();
}
H. Wang
  • 138
  • 4
  • 12
  • So where is the problem exactly, it seems to work ? If you want the exact behavior of the browser, you can use the require attribute on you html input. – Allan Raquin Oct 05 '15 at 16:42
  • I already used required field but I am using a hyper link instead of an input field with submit class, required field is not working. – H. Wang Oct 05 '15 at 16:44
  • May be you need `return false` after the alert since it's a link? – lshettyl Oct 05 '15 at 16:46
  • Instead of `alert` try `$('').hide().appendTo($('#form_1')).click().remove();` – Taleeb Oct 05 '15 at 16:51

1 Answers1

0

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

Community
  • 1
  • 1
Allan Raquin
  • 583
  • 7
  • 26