且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery使用条形码阅读器切换到下一个字段

更新时间:2022-05-31 06:08:42

您可以添加粘贴处理程序,拼接粘贴的文本,然后在相应字段上设置值,如本

You can add a paste handler, splice the pasted text, and then set the values on the appropriate fields as demonstrated in this JSFiddle.

注释:

  • 我将新的文本逻辑移到了一个新函数上,这样我就不必重复代码了.
  • 您可以详细了解 在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>