Tip: Click lines to highlight, hold ctrl/cmd to multi-select
Ajax validation plugin (4-Jan @ 17:57)
On keyup, sends the value of the specific input field to the form it's set within. By detecting the HTTPXREQUESTED_WITH header in the script the request is sent to, can allow you to send a specific response to the client.
Responses should be JSON and contain the following two attributes: ok {bool}, msg {string}
Syntax Highlighted Code
- (function ($) {
- $.fn.liveCheck = function () {
- return this.each(function () {
- var $$ = $(this);
- var t = this;
- var url = $$.parents('form:first').attr('action');
- var infospan = $$.parent().find('span');
- if (!infospan.length) {
- infospan = $$.after(' <span></span>').next();
- }
- $$.keyup(function () {
- // prevent tabbing in to the field firing an ajax hit
- if (t.value == '' && (t.lastValue == undefined)) return true;
- if (t.value != t.lastValue) {
- if (this.timer) clearTimeout(this.timer);
- infospan.removeClass('error').html('<img src="/images/ajax-loader.gif" height="16" width="16" /> validating...');
- this.timer = setTimeout(function () {
- $.ajax({
- url: url,
- data: t.name + '=' + t.value,
- dataType: 'json',
- type: 'post',
- success: function (j) {
- infospan.toggleClassIf(!j.ok, 'error').html(j.msg);
- }
- });
- }, 200);
- t.lastValue = t.value;
- }
- });
- });
- };
- $.fn.toggleClassIf = function (v, c) {
- return v ? this.addClass(c) : this.removeClass(c);
- };
- })(jQuery);
Plain Code
(function ($) {
$.fn.liveCheck = function () {
return this.each(function () {
var $$ = $(this);
var t = this;
var url = $$.parents('form:first').attr('action');
var infospan = $$.parent().find('span');
if (!infospan.length) {
infospan = $$.after(' <span></span>').next();
}
$$.keyup(function () {
// prevent tabbing in to the field firing an ajax hit
if (t.value == '' && (t.lastValue == undefined)) return true;
if (t.value != t.lastValue) {
if (this.timer) clearTimeout(this.timer);
infospan.removeClass('error').html('<img src="/images/ajax-loader.gif" height="16" width="16" /> validating...');
this.timer = setTimeout(function () {
$.ajax({
url: url,
data: t.name + '=' + t.value,
dataType: 'json',
type: 'post',
success: function (j) {
infospan.toggleClassIf(!j.ok, 'error').html(j.msg);
}
});
}, 200);
t.lastValue = t.value;
}
});
});
};
$.fn.toggleClassIf = function (v, c) {
return v ? this.addClass(c) : this.removeClass(c);
};
})(jQuery);