-
Notifications
You must be signed in to change notification settings - Fork 16
/
jquery-code-scanner.js
49 lines (44 loc) · 1.57 KB
/
jquery-code-scanner.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
(function ($) {
$.fn.codeScanner = function (options) {
var settings = $.extend({}, $.fn.codeScanner.defaults, options);
return this.each(function () {
var pressed = false;
var chars = [];
var $input = $(this);
$(window).keypress(function (e) {
var keycode = (e.which) ? e.which : e.keyCode;
if ((keycode >= 65 && keycode <= 90) ||
(keycode >= 97 && keycode <= 122) ||
(keycode >= 48 && keycode <= 57)
) {
chars.push(String.fromCharCode(e.which));
}
// console.log(e.which + ":" + chars.join("|"));
if (pressed == false) {
setTimeout(function () {
if (chars.length >= settings.minEntryChars) {
var barcode = chars.join('');
settings.onScan($input, barcode);
}
chars = [];
pressed = false;
}, settings.maxEntryTime);
}
pressed = true;
});
$(this).keypress(function (e) {
if (e.which === 13) {
e.preventDefault();
}
});
return $(this);
});
};
$.fn.codeScanner.defaults = {
minEntryChars: 8,
maxEntryTime: 100,
onScan: function ($element, barcode) {
$element.val(barcode);
}
};
})(jQuery);