Reputation: 2510
I am using jquery validation and to show the error messages using the bootstrap tooltips. This works fine, but when I insert an incorrect value in a not required field, and then delete the text and leave the field empty, the highlight effect in the input disappears but the tooltip remains visible.
JS
$('#myform').validate({ // initialize the plugin
onkeyup: false,
rules: {
field1: {
required: true,
number: true
},
field2: {
number: true
}
},
errorPlacement: function (error, element) {
var lastError = $(element).data('lastError'),
newError = $(error).text();
$(element).data('lastError', newError);
if (newError !== '' && newError !== lastError) {
$(element).tooltip({
placement: "bottom",
trigger: "manual"
}).attr('title', newError).tooltip('fixTitle').tooltip('show');
}
},
success: function (label, element) {
$(element).tooltip('hide');
}
});
HTML
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
To solve my problem I try to use unhighlight method, but only works the first time, then the tooltip is no longer displayed when re-insert an incorrect value in the same field
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass(errorClass).addClass(validClass);
$(element).tooltip('hide');
}
Type text in the 2nd field and than delete it. jsfiddle
How can I solve my problem? Thanks
Upvotes: 0
Views: 2734
Reputation: 167172
Could be considered a hack-job, but listening to the blur
event and clearing the tooltip if empty, works perfectly:
$("input").blur(function () {
if (!this.value.trim().length)
$(this).tooltip("hide");
});
Snippet
$('#myform').validate({ // initialize the plugin
onkeyup: false,
rules: {
field1: {
required: true,
number: true
},
field2: {
required: false,
number: true
}
},
errorPlacement: function(error, element) {
var lastError = $(element).data('lastError'),
newError = $(error).text();
$(element).data('lastError', newError);
if (newError !== '') {
$(element).tooltip({
placement: "bottom",
trigger: "manual"
}).attr('title', newError).tooltip('fixTitle').tooltip('show');
}
},
success: function(label, element) {
$(element).tooltip('hide');
}
});
$("input").blur(function() {
if (!this.value.trim().length)
$(this).tooltip("hide");
});
#myform {
width: 600px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
JsFiddle: https://jsfiddle.net/reo1ck3e/
Upvotes: 1