2

Basically, I have a form and a validation function that executes when a form is submitted. However, I want some other codes to run before the validation runs. I tried this: How to order events bound with jQuery, but it does not work.

Here's what I have:

  $('form').submit(function(){
    $('form').trigger('before-submit');

    if($(this).find('error').exists(event))
      event.preventDefault();
  });


  $('form').bind('before-submit', function(e) {
    if($('#url').val=='http://')
      $('#url').val('');
      alert('test');
  });
Community
  • 1
  • 1
Leo Jiang
  • 24,497
  • 49
  • 154
  • 284
  • Why not *literally* put a call to "some other codes" right before you do the validation? – jli Nov 25 '11 at 01:35
  • The first part is in an external file, the second part is generated with PHP. – Leo Jiang Nov 25 '11 at 02:12
  • You could still have a call to a function right before the validation, and then define that function somewhere else. – jli Nov 25 '11 at 02:13

2 Answers2

9

You could do:

$(function() {
     $('#formLogin').submit( function() {
         alert("Something"); //do something else here
         return true;
     });
});

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
  • 2
    This is not answer to this question and does not solve the problem in any way. – Martin Janeček Aug 24 '15 at 11:12
  • 1
    @MartinJaneček this code runs before form submit() executes, doesnt it..? and i guess this is wat OP wants... else i guess it would not be Accepted as correct answer..! – Sudhir Bastakoti Aug 24 '15 at 15:10
  • 1
    no, it doesnt - simulated it in [this fiddle](http://jsfiddle.net/envxddwa/) - `Something` will not show up before `external (validation)`. Commenting this right because it is Accepted as corrent answer while it doesn't solve asked problem. – Martin Janeček Aug 24 '15 at 19:08
0

how about this:

$('form').submit(function(){
  beforeSubmit(function(){
    // this function is the 'callback' function
    if($(this).find('error').exists(event))
      event.preventDefault();
  });
});

function beforeSubmit(fn) {
  if($('#url').val=='http://'){
    $('#url').val('');
    alert('test');
  }
  // call the 'callback' function you gave as argument
  fn();
}
Sander
  • 13,301
  • 15
  • 72
  • 97