Created
August 24, 2012 18:33
-
-
Save odyniec/3454084 to your computer and use it in GitHub Desktop.
Using a get valHook in a jQuery plugin
This file contains 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
(function ($) { | |
// jQuery plugin definition | |
$.fn.bytesInput = function () { | |
$(this).filter('input[type="text"]').each(function() { | |
$(this).data('bytesInput', true); | |
}); | |
return this; | |
}; | |
var origHook; | |
// There might already be valhooks for the "text" type | |
if ($.valHooks.text) | |
// Preserve the original valhook function | |
origHook = $.valHooks.text.get; | |
else | |
// Make room for a new valhook | |
$.valHooks.text = {}; | |
$.valHooks.text.get = function (el) { | |
// Does this element have our data field? | |
if (!$(el).data('bytesInput')) | |
// No -- check if there was a valhook function already defined | |
if (origHook) | |
// There was, so go ahead and call it | |
return origHook(el); | |
else | |
// No previous function, return undefined to have jQuery | |
// take care of retrieving the value | |
return undefined; | |
// Try parsing the expression | |
if (matches = el.value.match(/(\d+)\s*([kKmMgG]?)[bB]?/)) { | |
switch (matches[2].toLowerCase()) { | |
case 'k': | |
// Kilobytes | |
return matches[1] * 1024; | |
case 'm': | |
// Megabytes | |
return matches[1] * 1048576; | |
case 'g': | |
// Gigabytes | |
return matches[1] * 1073741824; | |
default: | |
// Just bytes | |
return matches[1]; | |
} | |
} | |
else | |
// Can't parse the expression -- just return the current value | |
return el.value; | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment