jquery-code-scanner.js 1.6 KB

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