in Jquery how to run code with callback before submit

You should use the submit event on the form, not the click event of the button. Some browsers allow the form to be submitted without using the submit button by just pressing enter when some field in the form has focus.

The preventDefault method will stop the submitting of the form, so that you can submit it later:

$("form").submit(function(e){
  e.preventDefault();
  var address = $(this).find('.address').val();
  geocoder.geocode( { 'address': unescape(address)}, function(results, status) 
  {
      if (status == google.maps.GeocoderStatus.OK) 
      {
        $(".latSelector input:hidden").val(results[0].geometry.location.lat());
        $(".lngSelector input:hidden").val(results[0].geometry.location.lng());
        $("form")[0].submit();
      }
   });  
});

Edit:

To submit the form using the button, you need to keep track of why the form is submitted:

var reason = 'user';

$("form").submit(function(e){
  if (reason == 'user') {
    e.preventDefault();
    var address = $(this).find('.address').val();
    geocoder.geocode( { 'address': unescape(address)}, function(results, status) 
    {
      if (status == google.maps.GeocoderStatus.OK) 
      {
        $(".latSelector input:hidden").val(results[0].geometry.location.lat());
        $(".lngSelector input:hidden").val(results[0].geometry.location.lng());
        reason = 'callback';
        $("form input:submit").click();
      }
    });
  }
});

Leave a Comment