1 module( 'jquery.byteLimit.js' );
3 test( '-- Initial check', function() {
5 ok( $.fn
.byteLimit
, 'jQuery.fn.byteLimit defined' );
8 // Basic sendkey-implementation
9 $.addChars = function( $input
, charstr
) {
10 var len
= charstr
.length
;
11 for ( var i
= 0; i
< len
; i
++ ) {
12 // Keep track of the previous value
13 var prevVal
= $input
.val();
16 var code
= charstr
.charCodeAt(i
);
18 // Trigger event and undo if prevented
19 var event
= new jQuery
.Event( 'keypress', { keyCode
: code
, which
: code
, charCode
: code
} );
20 $input
.trigger( event
);
21 if ( !event
.isDefaultPrevented() ) {
22 $input
.val( prevVal
+ charstr
[i
] );
28 * Test factory for $.fn.byteLimit
30 * @param $input {jQuery} jQuery object in an input element
31 * @param useLimit {Boolean} Wether a limit should apply at all
32 * @param limit {Number} Limit (if used) otherwise undefined
33 * The limit should be less than 20 (the sample data's length)
35 var byteLimitTest = function( options
) {
46 test( opt
.description
, function() {
48 opt
.$input
.appendTo( 'body' );
50 // Simulate pressing keys for each of the sample characters
51 $.addChars( opt
.$input
, opt
.sample
);
52 var newVal
= opt
.$input
.val();
57 ltOrEq( $.byteLength( newVal
), opt
.limit
, 'Prevent keypresses after byteLimit was reached, length never exceeded the limit' );
58 equal( $.byteLength( newVal
), opt
.expected
, 'Not preventing keypresses too early, length has reached the expected length' );
62 equal( $.byteLength( newVal
), opt
.expected
, 'Unlimited scenarios are not affected, expected length reached' );
70 // Simple sample (20 chars, 20 bytes)
71 simpleSample
= '12345678901234567890',
73 // 3 bytes (euro-symbol)
76 // Multi-byte sample (22 chars, 26 bytes)
77 mbSample
= '1234567890' + U_20AC
+ '1234567890' + U_20AC
;
80 description
: 'Plain text input',
81 $input
: $( '<input>' )
87 expected
: $.byteLength( simpleSample
)
91 description
: 'Limit using the maxlength attribute',
92 $input
: $( '<input>' )
105 description
: 'Limit using a custom value',
106 $input
: $( '<input>' )
111 sample
: simpleSample
,
118 description
: 'Limit using a custom value, overriding maxlength attribute',
119 $input
: $( '<input>' )
125 sample
: simpleSample
,
132 description
: 'Limit using a custom value (multibyte)',
133 $input
: $( '<input>' )
141 expected
: 14 // (10 x 1-byte char) + (1 x 3-byte char) + (1 x 1-byte char)
145 description
: 'Limit using a custom value (multibyte) overlapping a byte',
146 $input
: $( '<input>' )
154 expected
: 12 // 10 x 1-byte char. The next 3-byte char exceeds limit of 12, but 2 more 1-byte chars come in after.