问题
Is it possible to integrate the jquery validator with a some sort of tooltip?
Here is what I am trying to do: I have a contact form, onfocus of any fields, I want a real time tooltip to appear that directs the visitor into what to type, and once the tooltip is happy with the field value, it displays "accepted". Until then it reports an error e.g. "Name must be at least 5 characters", or "You must enter a valid email address."
Then on submit I want to show these tooltips for all the ones that were not accepted. I also want them to fadeIn and animate the same way as when on onfocus. I also want these tooltips to fadeout, when I am infocus for one of the fields, and the field I am infocus cannot run through the animation of fadeIn, as it is already displayed.
Any ideas of how to do this easily?
回答1:
Here is all what you need, it has animation too >> FIDDLE Example
HTML
<input type="text" id="txt1" />
<input type="text" id="txt2" />
<div id="tt"></div>
CSS
#tt{width:0px; height:0px; visibility':hidden; margin-left: -500px; background-color:red;}
jQuery
$('#txt1').focus(function(){
$('#tt').css({'width':'200px', 'height':'50px', 'visibility':'visible', 'background-color':'red'}).html('you clicked text field ONE').animate({'marginLeft':'10px'},1000)
});
$('#txt2').focus(function(){
$('#tt').css({'width':'300px', 'height':'50px', 'visibility':'visible', 'background-color':'yellow'}).html('you clicked text field TWO').animate({'marginLeft':'150px'},1000)
});
回答2:
Working Demo: http://jsfiddle.net/bvu5f/
This answer uses a jQuery plugin called Tooltipster along with the jQuery Validate plugin.
First, initialize the Tooltipster plugin (with any options) on all specific form elements that will display errors:
$(document).ready(function () {
// initialize tooltipster on form input elements
$('#myform input[type="text"]').tooltipster({
trigger: 'custom', // default is 'hover' which is no good here
onlyOne: false, // allow multiple tips to be open at a time
position: 'right' // display the tips to the right of the element
});
});
Second, use Tooltipster's advanced options along with the success: and errorPlacement: callback functions built into the Validate plugin to automatically show and hide the tooltips as follows:
$(document).ready(function () {
// initialize validate plugin on the form
$('#myform').validate({
// any other options & rules,
errorPlacement: function (error, element) {
$(element).tooltipster('update', $(error).text());
$(element).tooltipster('show');
},
success: function (label, element) {
// $(element).tooltipster('hide'); // normal validate behavior
$(element).tooltipster('update', 'accepted'); // as per OP
}
});
});
Code takes advantage of the new Tooltipster API features released in version 2.1 on 2/12/13
来源:https://stackoverflow.com/questions/16408449/jquery-validator-with-tooltip