JQuery to navigate to next field using barcode reader
So now I have the following code that adds a new input text field after you start typing it and it moves the cursor to the next one when it detects an exclamation mark (!). However! the character is not detected when using the copy / paste function or when using a barcode reader to fill in the field. Is there a way to resolve this?
$('#myDiv').on('keyup', 'input', function (e) {
if ($(this).val() == '') {
$(this).next().remove();
return;
} else if ($(this).next().val() == '') {
if (e.keyCode === 49 && e.shiftKey) {
$(this).next().focus();
}
return;
}
var newTxt = $(this).clone();
var id = newTxt.attr('id');
newTxt.attr('id', 'txt_' + (parseInt(id.substring(id.indexOf('_') + 1))));
newTxt.val('');
$(this).parent().append(newTxt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="myDiv">
<input type="text" name="qr[]" id="txt_1" autofocus />
</div>
+1
source to share
1 answer
You can add an insert handler, splice the nested text, and then set the values ββin the appropriate fields as shown in this JSFiddle .
Notes:
- I moved the new textual logic into a new function so that I don't have to duplicate code.
- You can read more about the
split
feature on MDN .
$('#myDiv').on('keyup', 'input', function(e) {
if ($(this).val() == '') {
$(this).next().remove();
return;
} else if ($(this).next().val() == '') {
if (e.keyCode === 49 && e.shiftKey) {
$(this).next().focus();
}
return;
}
addNewTxt($(this));
});
$('#myDiv').on('paste', 'input', function(e) {
e.preventDefault();
var text = (e.originalEvent || e).clipboardData.getData('text/plain');
if (!text) {
return;
}
var textSections = text.split('!');
$(this).val(textSections[0]);
var lastEl;
for (var i = 1; i < textSections.length; i++) {
lastEl = addNewTxt($(this), textSections[i]);
}
lastEl.focus();
});
function addNewTxt(el, val) {
var newTxt = el.clone();
var id = newTxt.attr('id');
newTxt.attr('id', 'txt_' + (parseInt(id.substring(id.indexOf('_') + 1))));
newTxt.val(val || '');
el.parent().append(newTxt);
return newTxt;
}
<div id="myDiv">
<input type="text" name="qr[]" id="txt_1" autofocus />
</div>
+1
source to share