I have this code that triggers when a form is submitted:
$("form").submit(function (e) {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("Address").value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$("#LatitudeLongitude").val(results[0].geometry.location);
$("form").submit();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
$('form').unbind('submit');
return false;
});
What it does: it calls google geocoding service to translate an address into latitude/longitude which is set into a hidden field of the form. If there is a result, then the form is submitted.
The problem is that if validation fails (for instance a required field has not been set) then the call to geocoding is still made. Moreover, if I click a second time on the submit button, even if the required field has not been set, the form is posted.
How can I call the geocoding service only if the unobtrusive validation has been successful?
Rather than attaching to the
submit()event, you need to capture an earlier event, and exercise control over how to proceed.First, let’s assume your original button has an id of
submitand you create a new submit button with an id ofstartSubmit. Then, hide the original submit button by setting the HTML attributedisplay="false". Next, bind to theclickevent of your new button, and add your code, as modified:This will invoke validation, so that geocoding will only occur if the form is valid, then, after geocoding has returned a response, it will submit the form by incoking the click event on the submit button.