4 * @author Jan Paul Posma
9 * Enforces a byte limit to a textbox, so that UTF-8 entries are counted as well, when, for example,
10 * a databae field has a byte limit rather than a character limit.
11 * Plugin rationale: Browser has native maxlength for number of characters, this plugin exists to
12 * limit number of bytes instead.
14 * Can be called with a custom limit (to use that limit instead of the maxlength attribute value),
15 * a filter function (in case the limit should apply to something other than the exact input value),
16 * or both. Order of arguments is important!
18 * @context {jQuery} Instance of jQuery for one or more input elements
19 * @param limit {Number} (optional) Limit to enforce, fallsback to maxLength-attribute,
20 * called with fetched value as argument.
21 * @param fn {Function} (optional) Function to call on the input string before assessing the length
22 * @return {jQuery} The context
24 $.fn
.byteLimit = function( limit
, fn
) {
25 // If the first argument is the function,
26 // set fn to the first argument's value and ignore the second argument.
27 if ( $.isFunction( limit
) ) {
32 // Default limit to current attribute value
33 if ( limit
=== undefined ) {
34 limit
= this.attr( 'maxLength' );
36 // If limit passed, update/set attribute value instead
38 this.attr( 'maxLength', limit
);
41 // Nothing passed and/or empty attribute, return without binding an event.
42 if ( limit
=== undefined ) {
46 // Save function for reference
47 this.data( 'byteLimit-callback', fn
);
49 // We've got something, go for it:
50 return this.keypress( function( e
) {
51 // First check to see if this is actually a character key
53 // Based on key-event info from http://unixpapa.com/js/key.html
54 // jQuery should also normalize e.which to be consistent cross-browser,
55 // however the same check is still needed regardless of jQuery.
57 // Note: At the moment, for some older opera versions (~< 10.5)
58 // some special keys won't be recognized (aka left arrow key).
59 // Backspace will be, so not big issue.
61 if ( e
.which
=== 0 || e
.charCode
=== 0 || e
.which
=== 8 ||
62 e
.ctrlKey
|| e
.altKey
|| e
.metaKey
)
64 return true; //a special key (backspace, etc) so don't interfere.
67 var val
= fn
!== undefined ? fn( $( this ).val() ): $( this ).val(),
68 len
= $.byteLength( val
),
69 // Note that keypress returns a character code point, not a keycode.
70 // However, this may not be super reliable depending on how keys come in...
71 charLen
= $.byteLength( String
.fromCharCode( e
.which
) );
73 if ( ( len
+ charLen
) > limit
) {