我有一个简单的表单,用户可以在其中输入地址。
在提交表单之前,我使用 Places Api 执行 TextSearch 并将此数据放入表单中的隐藏输入字段中,然后提交。
我想使用 jQuery Validate 来验证表单,但我不知道如何将 Places 数据与它一起获取。
我想我必须将 submitHandler 与 Validate 一起使用,但我不确定如何将我的代码放在这里:
$("#myform").validate({
submitHandler: function(form) {
form.submit();
}
});
这是我没有验证插件的代码:
<!DOCTYPE html>
<html>
<head>
<title>Maps Test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var map;
var service;
var infowindow;
var service;
var validated = false;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
service = new google.maps.places.PlacesService(map);
}
function textsearchcallback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var place = results[0];
var request = {
reference: place.reference
};
service.getDetails(request, getdetailscallback);
} else {
alert("ERROR: NO RESULTS FOUND!");
}
}
function getdetailscallback(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
$("#placeinfo").val(JSON.stringify(place));
validated = true;
$("#search-form").submit();
validated = false;
$("#placeinfo").val("");
} else {
alert("ERROR");
}
}
function validateForm() {
var searchfield = $("#search-field").val();
if (searchfield == null || searchfield == "") {
alert("Please enter address");
return false;
}
if (validated) {
return true;
} else {
var request = {
query: searchfield
};
service.textSearch(request, textsearchcallback);
return false;
}
}
</script>
</head>
<body onload="initialize()">
<form id="search-form" name="input" action="html_form_action.asp" method="get" onsubmit="return validateForm()">
<input autocomplete="off" placeholder="Address, Airport or Postcode..." id="search-field" size="50" type="text"><br>
<input type="hidden" name="placeinfo" id="placeinfo">
<input type="SUBMIT" value="Search" /><br>
</form>
<div id="map_canvas" style="width:600px; height:400px"></div>
</body>
</html>
编辑:
这是一个带有工作代码的小提琴:http: //jsfiddle.net/robertdodd/txqnL/26/