Created
July 14, 2010 12:09
-
-
Save mpj/475338 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
JUMPYFIELD is a simple little thing that makes the focus jump between fields when they reach maxlength. | |
Usage: | |
$(".myInputFields").jumpy(); | |
jumpy also accepts an optional array of default values that count the fields as "empty". Example: | |
$(".myInputFields").jumpy(["YY","MM","DD"]); | |
*/ | |
jQuery.fn.jumpy = function(defaultValues) { | |
// Save the context in the element so that we know which fields to jump between. | |
this.data("_jumpySelector", this.selector); | |
this.keyup(function(event) { | |
var tabKeyCode = 9; | |
if (event.keyCode == tabKeyCode) { | |
// Ignore accidental tabbing as a result of the user not knowing about the | |
// jumpy fields, and trying to tab after filling out a field. | |
var previousJumpy = jQuery(this)._getPreviousJumpyField(); | |
var isEmpty = jQuery(previousJumpy).val().length == 0; | |
var hasDefaultValue = jQuery(previousJumpy).data("_defaultValue") == jQuery(previousJumpy).val(); | |
if ( isEmpty || hasDefaultValue ) | |
previousJumpy.focus(); | |
return false; | |
} | |
if (jQuery(this).val().length >= parseInt(jQuery(this).attr("maxlength"))) { | |
var nextjf = jQuery(this)._getSubsequentJumpyField(); | |
jQuery(nextjf).focus(); | |
} | |
}); | |
}; | |
jQuery.fn._getSubsequentJumpyField = function() { | |
var lastIterated = null; | |
var subsequent = null; | |
var originator = this[0]; | |
jQuery(this.data("_jumpySelector")).each(function(index, iterated) { | |
if (subsequent == null) { | |
if (lastIterated == originator) { | |
subsequent = this; | |
} | |
lastIterated = this; | |
} | |
}); | |
return subsequent; | |
} | |
jQuery.fn._getPreviousJumpyField = function () { | |
var lastIterated = null; | |
var previous = null; | |
var originator = this[0]; | |
console.log("getting prev field for " + this.data("_jumpySelector")); | |
jQuery(this.data("_jumpySelector")).each(function(index, iterated) { | |
if (previous == null) { | |
if (this == originator) { | |
previous = lastIterated; | |
} | |
lastIterated = this; | |
} | |
}); | |
console.log("found" + previous); | |
return previous; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment