Skip to content

Instantly share code, notes, and snippets.

@tuchanemo
Last active October 9, 2018 13:14
Show Gist options
  • Save tuchanemo/e1926a19b427e68ceac34ac568521c3d to your computer and use it in GitHub Desktop.
Save tuchanemo/e1926a19b427e68ceac34ac568521c3d to your computer and use it in GitHub Desktop.
barcode
<!-- https://code.mu -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Это заголовок тайтл</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div>
<div style="font-family: sans-serif;
font-weight: bold;">
Test Input 1:<br>
<input type="text"
value=""
name="firstname"
id="quantity"
>
<br>
Test Input 2:<br>
<input type="text"
value=""
name="firstname1"
id="quantity1"
>
<br>
Scan Bar code:<br>
<input type="text"
value=""
name="you_bar_code"
id="you_bar_code"
readonly>
<button type="button" id="clear">
Очистить
</button>
</div>
<div id="barc">
</div>
</div>
<script src="js/jquery.js"></script>
<script src="js/main.js"></script>
</body>
</html>
$(document).ready(function () {
$("#clear").on("click", function () {
$("#barc").empty();
$("#quantity").val('');
$("#quantity1").val('');
})
var pressed = false;
var chars = [];
var barcode;
$(document).keypress(function (e) {
//console.log(e.which);
if ( e.which == 13 ||
(e.which >= 32 && e.which <= 126) ||
(e.which >= 128 && e.which <= 255) ||
(e.which >= 1040 && e.which <= 1103)
) {
chars.push(String.fromCharCode(e.which));
if (pressed == false) {
setTimeout(function () {
if (chars.length >= 10) {
barcode = chars.join("");
//barcode = "wwe4544543kjgdmапвапПрGTQогра-==\№;%::?*";
barcode = barcode.replace(/[^0-9a-zA-Z]/gim, '');
$("#barc").append(barcode + "<br>");
$('#you_bar_code').val(barcode);
} else {
var focused = document.activeElement;
if (!focused || focused == document.body)
focused = null;
else if (document.querySelector) {
focused = document.querySelector(":focus");
var pos = focused.selectionStart;
//console.log(pos);
var barcode = chars.join("");
if (!$(focused).is('[readonly]')) {
var current = $(focused).val();
var newVal = current.substr(0, pos) + barcode + current.substr(pos);
// Вычисляем новую позицию курсора
var newPos = pos + barcode.length;
$(focused).val(newVal);
// Выставляем курсор в позицию от начала строки
$(focused).get(0).setSelectionRange(newPos, newPos);
}
}
}
chars = [];
pressed = false;
}, 300);
}
pressed = true;
return false;
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment