I have a form which collects some data, most importantly an address which needs to be geocoded to obtain the lat and long.
Suppose the user inputs something like:
123 main st
SomEwheRE, NY 12345
My client-side javasript goes out to the Google Geocoding service and attempts to get the lat and long for that address. In return I also get back more addition information including the properly formatted address:
123 Main St
Somewhere, NY 12345
What I want to do is replace the values in their respective textboxes so that the user can verify the data is good and then finally submit via jQuery.post("My/Controller/", myJSONData, function(){}); but I’m getting some strange behavior.
If I type in an address and don’t include a zip code (it’s required in the database but not necessary to geocode the address) I get a validation error. The thing is I would like to defer validation until after I obtain the information from the geocode service and replace the values in the textbox.
Right now, if I only type in a partial address (and hit “Submit”) this is what happens:
- Validation errors occur on the missing required fields and all my textboxes go blank
- Hit submit again and this time the textboxes are properly filled in with the geocoded information BUT ALL fields produce validation errors.
- Hit submit a 3rd time and now the validation errors go away and everything is as expected. At this point, I want to consider the form valid and allow the
POSTto theController.
Code:
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault();
var geoCodedAddress = geoCodeAddress($("#Address1").val(), $("#City").val(), $("#State").val());
console.log(geoCodedAddress);
geoCodedAddress.Name = $("#Name").val();
geoCodedAddress.Phone = $("#Phone").val();
$("#Address1").val(geoCodedAddress.Address1);
$("#City").val(geoCodedAddress.City);
$("#State").val(geoCodedAddress.State);
$("#ZipCode").val(geoCodedAddress.ZipCode);
});
});
geoCodeAddress() returns the JSON object with the required fields filled in and that works. I believe the problem lies somewhere between my ineptitude and the block of code I posted.
Well, after much tinkering this is what I came up with. Basically, when someone hits submit (or enter) I stop the form from being submitted (by
e.preventDefault()) and check to see if it’s valid. If the form data is valid, I then process what the user entered, fill in the form fields with the acquired data (this doesn’t do anything functional, it just flashes the new data in the form). I couldn’t figure out how to submit the form, so I posted it myself using$.post(). If there is a better way please leave a comment or answer and I will vote. Here is my complete code: