hi, I'm doing some geocoding using the google maps API. The user fill a form with some address, and when the submit button is clicked, a codeAddress() function is called, which is supposed to perform the geocoding, but it does not work. As a test, I hardcoded the address and call the codeAddress function when the document is loaded. When codeAddress is called when the page is ready, it works ok, but when it's called by the onclick event, it doesn't work (no errors returned by firebug, but it's like the geocoding service is not called). When I remove the form tags, it works too... What's the problem with calling this function on onclick of a submit button of a form?. Anybody can help? Thanks the javascript $(function(){ codeAddress(); }); function codeAddress() { var geocoder = new google.maps.Geocoder(); var address = "paseo montjuic, 30, barcelona, spain"; if (geocoder) { geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { alert(results[0].geometry.location.lat()); } else { alert("Geocode was not successful for the following reason: " + status); } }); } } Code (markup): the HTML <form action="/restaurant/add/" method="POST"> <!-- stuff --> <p style="clear: both;"><input type="submit" value="Submit" onclick="codeAddress()" /></p> </form> HTML:
you need to return false; onclick="codeAddress(); return false;" The form is submitting and the form is being posted, therefore a new page is being loaded and your javascript is executing but it won't make a difference.
do you use jquery or another framework here? (the $(anon function) seems to make me think you do). change the form and add an id, like id="foo" remove the onclick= from the button, handle the form event instead: i am not a native jquery dev though, if this were mootools i'd use new Event(e).stop(); instead as its more compatible in stopping event bubbling $("#foo").submit(function(e) { e.preventDefault(); // stops event propagation. - check if it works in ie and opera var geocoder = new google.maps.Geocoder(); var address = "paseo montjuic, 30, barcelona, spain"; if (geocoder) { geocoder.geocode({ 'address': address }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { alert(results[0].geometry.location.lat()); } else { alert("Geocode was not successful for the following reason: " + status); } }); } }); Code (javascript): anyway - failing that you may want to post some more code, like a working model or something.
Sorry, onclick="codeAddress(); return false; does work. yes, I'm using jQuery, and you're right ?m going to use $("#foo").submit for cleaner code. Thanks