4 * @author Jan Paul Posma
9 * Enforces a byte limit to a textbox, so that UTF-8 entries are not arbitrarily truncated.
11 $.fn
.byteLimit = function( limit
) {
13 // Default to current attribute value
14 if ( limit
== null ) {
15 limit
= this.attr( 'maxLength' );
17 // If passed, update/set attribute value instead
19 this.attr( 'maxLength', limit
);
22 // Nothing passed and/or empty attribute, return without binding an event.
23 if ( limit
== null ) {
27 // We've got something, go for it:
28 return this.keypress( function( e
) {
29 // First check to see if this is actually a character key
31 // Based on key-event info from http://unixpapa.com/js/key.html
32 // jQuery should also normalize e.which to be consistent cross-browser,
33 // however the same check is still needed regardless of jQuery.
35 // Note: At the moment, for some older opera versions (~< 10.5)
36 // some special keys won't be recognized (aka left arrow key).
37 // Backspace will be, so not big issue.
39 if ( e
.which
=== 0 || e
.charCode
=== 0 || e
.which
=== 8 ||
40 e
.ctrlKey
|| e
.altKey
|| e
.metaKey
)
42 return true; //a special key (backspace, etc) so don't interfere.
45 var len
= $.byteLength( this.value
);
46 // Note that keypress returns a character code point, not a keycode.
47 // However, this may not be super reliable depending on how keys come in...
48 var charLen
= $.byteLength( String
.fromCharCode( e
.which
) );
50 if ( ( len
+ charLen
) > limit
) {