我在表单中使用谷歌自动完成和jQuery验证,它适用于以下情况。
以上条件工作正常。但
please enter the location
(请查看下图)。当用户单击某处或将光标移动到下一个字段时,只有错误消息变为隐藏。如果用户通过单击“输入”选择该值,则在选择值时不应显示错误消息。如果未选择值,则显示错误消息就可以了。
请帮我。 DEMO
$( "form" ).validate({
focusInvalid: false,
submitHandler: function() {
alert( "Successful submission" );
}
});
$("#locationTextField").on("blur", function () { 0 == $(this).val().trim().length ? ($("#locationTextField").parents("div").removeClass("has-error").addClass("success"), $("#locationTextField-error").hide()) : $("#locationTextField").removeClass("success").addClass("has-error")
});
form > div {
margin: 1em;
}
form button {
width: 100%;
}
label { display: block; }
input {
width: 100%;
padding: 0.2em;
}
button {
padding: 0.2em;
}
label.error {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&dummy=.js"></script>
<form>
<div>
<label for="name">Location:</label>
<input type="text" id="locationTextField" style="color:#555 !important;" onChange="return validateCity()" placeholder="" name="location" class="form-control" required maxlength="150" data-msg-required="Please enter your location">
</div>
<div>
<label for="name">Name:</label>
<input type="text" placeholder="" name="name" class="form-control" required maxlength="150" data-msg-required="Please enter your name">
</div>
<div>
<button>Submit</button>
</div>
</form>
<script>
function initialize() {
var e = document.getElementById("locationTextField");
new google.maps.places.Autocomplete(e);
}
google.maps.event.addDomListener(window, "load", initialize);
function validateCity() {
return searchfield = $("#locationTextField").val(), "" == searchfield || null == searchfield ? !1 : ($("#locationTextField").val(""), !1)
}
</script>
整个问题是由jQuery Validate插件仅由用户交互(如onkeyup
,focusout
等)触发的事实引起的。由于您以编程方式更改此字段的值,因此始终会跳过验证。
解决方案只需使用插件的.valid()
方法以编程方式触发验证。但是,由于该字段由Google自动填充功能填充,因此您需要找到可用于调用.valid()
的内置事件。 Google提供适用于此的place_changed
活动。
place_changed
事件的Google侦听器。.valid()
。该字段将被验证,错误将自动显示/隐藏。onChange
功能。这不是必需的。validateCity
功能。它也不需要。blur
处理函数。由于插件旨在自动处理这些更改,因此不需要它。新代码:
function initialize() {
var e = document.getElementById("locationTextField");
var autocomplete = new google.maps.places.Autocomplete(e);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
$('#locationTextField').valid(); // trigger validation after place selected
});
}
google.maps.event.addDomListener(window, "load", initialize); // initialize Google Maps
$("form").validate({ // initialize Validate plugin
// options
});
但是:ぁzxswい