Adding support for a callback to jquery.byteLimit
[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 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.
13 *
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!
17 *
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
23 */
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 ) ) {
28 fn = limit;
29 limit = undefined;
30 }
31
32 // Default limit to current attribute value
33 if ( limit === undefined ) {
34 limit = this.attr( 'maxLength' );
35
36 // If limit passed, update/set attribute value instead
37 } else {
38 this.attr( 'maxLength', limit );
39 }
40
41 // Nothing passed and/or empty attribute, return without binding an event.
42 if ( limit === undefined ) {
43 return this;
44 }
45
46 // Save function for reference
47 this.data( 'byteLimit-callback', fn );
48
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
52 // being pressed.
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.
56
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.
60
61 if ( e.which === 0 || e.charCode === 0 || e.which === 8 ||
62 e.ctrlKey || e.altKey || e.metaKey )
63 {
64 return true; //a special key (backspace, etc) so don't interfere.
65 }
66
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 ) );
72
73 if ( ( len + charLen ) > limit ) {
74 e.preventDefault();
75 }
76 });
77 };
78
79 } )( jQuery );