byteLimit/byteLength improvements:
[lhc/web/wiklou.git] / resources / jquery / jquery.byteLimit.js
1 /**
2 * jQuery byteLimit
3 *
4 * @author Jan Paul Posma
5 */
6 ( function( $ ) {
7
8 /**
9 * Enforces a byte limit to a textbox, so that UTF-8 entries are not arbitrarily truncated.
10 */
11 $.fn.byteLimit = function( limit ) {
12
13 // Default to current attribute value
14 if ( limit == null ) {
15 limit = this.attr( 'maxLength' );
16
17 // If passed, update/set attribute value instead
18 } else {
19 this.attr( 'maxLength', limit );
20 }
21
22 // Nothing passed and/or empty attribute, return without binding an event.
23 if ( limit == null ) {
24 return this;
25 }
26
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
30 // being pressed.
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.
34
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.
38
39 if ( e.which === 0 || e.charCode === 0 || e.which === 8 ||
40 e.ctrlKey || e.altKey || e.metaKey )
41 {
42 return true; //a special key (backspace, etc) so don't interfere.
43 }
44
45 var len = $.byteLength( this.value );
46
47 // limit-3 as this doesn't count the character about to be inserted.
48 if ( len > ( limit-3 ) ) {
49 e.preventDefault();
50 }
51 });
52 };
53
54 } )( jQuery );