Я пишу приложение, которое работает на клавиатуре, но в основном как приложение со штрих-кодом. Я с трудом очищаю некоторые поля для сброса формы после каждой отправки кнопки, а также перефокусируюсь на правильное поле (пустое)
Вот как это выглядит
Идентификатор грузоотправителя не очищается, если я не нажму эту черную кнопку или не отсканирую штрих-код со значением *CloseShipper*
. Он также загружается пустым при первой загрузке страницы.
Поле Tracking # очищается и получает фокус, когда я нажимаю кнопку «Добавить в пакет» или сканирую штрих-код со значением *AddToBatch*
.
Поле «Штрих-код приложения» очищается сразу после того, как я сканирую приложение и добавляю его в массив, который отображается под ним, и получает правильный фокус для продолжения непрерывного сканирования до тех пор, пока я не закончу процесс, щелкнув или отсканировав команду «Добавить в пакет». (Эта часть работает)
Моя проблема в том, что когда я сканирую штрих-код *AddToBatch*
, ничего не происходит. Если я щелкаю по нему, событие click регистрируется, и оно очищает поля, которые необходимо очистить, но фокус все еще остается на коде приложения. Итак, это две проблемы в отдельности.
Извините, я не могу воспроизвести рабочую скрипку. Слишком много зависимостей для работы. Поэтому я выложу соответствующий код здесь.
Шаблон:
<form class="uk-form-horizontal uk-margin-medium barcodefields">
<div v-if="reset">
<div class="uk-margin">
<label
class="uk-form-label"
:for="_uid+'ctsinput'">
Shipper ID
</label>
<div class="uk-form-controls">
<input
class="uk-input"
:id="_uid+'ctsinput'"
name="shippernumber"
type="text"
maxlength="24"
:autofocus="'autofocus'"
v-focus
v-model.trim="shipperbarcode"
@input="runException"
/>
</div>
</div>
<div class="uk-margin">
<label
class="uk-form-label"
:for="_uid+'ctsinput'">
Tracking #
</label>
<div class="uk-form-controls">
<input
class="uk-input"
:id="trackingNumber"
name="trackingnumber"
type="text"
maxlength="24"
v-model.trim="trackingbarcode"
@input="runException"
/>
</div>
</div>
<div class="uk-margin">
<label
class="uk-form-label"
:for="_uid+'ctsinput'">
App. Barcode #
</label>
<div class="uk-form-controls">
<input
class="uk-input"
:id="_uid+'ctsinput'"
name="appbarcode"
type="text"
maxlength="24"
v-model.trim="applicationbarcode"
@change="addApplication"
/>
</div>
</div>
<!-- This is the list of apps scanned -->
<h5
v-if="this.appList.length !== 0"
class="heading-app-scanned"
>Applications Scanned In This Batch</h5>
<div
v-if="this.appList.length !== 0"
class="uk-card uk-card-secondary app-collection"
>
<div
v-for="appItem in appList"
:key="appItem.id"
class="app-scanned-item">
<div class="uk-padding-small">
<label class="uk-form-label">Application #:</label>
<span class="uk-text">{{appItem}}</span>
</div>
<div class="uk-divider"></div>
</div>
</div>
</div>
</form>
В моих скриптах, кроме всех реквизитов, данных и т. Д., Есть логическая часть:
methods: {
...mapActions(["fetchBatches"]),
// evaluating the value of the shipperbarcode and trackingbarcode
runException: function(e) {
this.shipperbarcode = this.shipperbarcode.replace(/[^0-9.]/g, "");
this.trackingbarcode = this.trackingbarcode.replace(/[^0-9.]/g, "");
},
// evaluating what happens when an app is scanned
addApplication: function(e) {
let appBar = this.applicationbarcode;
if (
this.applicationbarcode === "*AddToBatch*" ||
this.applicationbarcode === "*CloseShipper*"
) {
this.applicationbarcode = "";
return;
} else {
this.counter += 1;
}
//give access to the add to batch function to trigger the modal window and close batch
this.addToBatch();
// send the qualifying barcodes to an array and clear the field for the next scan
this.appList.push(this.applicationbarcode);
//give focus to the tracking number after a batch has been made
document.addEventListener("change", function(appBar) {
if (appBar === "*AddToBatch*") {
this.appList = [];
this.shipperbarcode = document.querySelector(
"input[name=shippernumber]"
).value;
this.trackingbarcode = "";
let hasFocus = document.querySelector("input[name=trackingnumber]");
hasFocus.focus();
// after entering a new tracking number pass the focus to the barcode input
if (hasFocus.value.length > 0) {
hasFocus = document.querySelector("input[name=appbarcode]");
hasFocus.focus();
} else {
hasFocus = document.querySelector("input[name=trackingnumber]");
hasFocus.focus();
}
}
});
this.applicationbarcode = "";
this.applicationbarcode = this.applicationbarcode.replace(/[^0-9.]/g, "");
},
addedToBatch: function() {
this.addToBatch("*AddToBatch*");
},
// When the add to batch button is scanned
addToBatch: function(appBar) {
// open the modal if the counter is above 25. This will be rewritten to read from server as the 25 can differ
if (this.counter >= 25) {
UIkit.modal("#closeBatchDialog").show();
}
// if the counter is > 0 show the close batch button
if (this.counter > 0) {
this.finishBatch = true;
}
// If the app barcode is Add to Batch barcode give shipper # input field the value it already has
// and clear the tracking number field. ********** Must exist for click event
if (appBar === "*AddToBatch*") {
this.appList = [];
this.shipperbarcode = document.querySelector(
"input[name=shippernumber]"
).value;
this.trackingbarcode = "";
//give focus to the tracking number after a batch has been made
let hasFocus = document.querySelector("input[name=trackingnumber]");
hasFocus.focus();
// after entering a new tracking number pass the focus to the barcode input
if (hasFocus.value.length > 0) {
hasFocus = document.querySelector("input[name=appbarcode]");
hasFocus.focus();
} else {
hasFocus = document.querySelector("input[name=trackingnumber]");
hasFocus.focus();
}
}
},
// if the close shipper barcode is scanned
closeShipper: function(e) {
// if the barcode for close shipper is scanned
if (this.applicationbarcode === "*CloseShipper*") {
// clear all fields
this.appList = [];
this.shipperbarcode = "";
this.trackingbarcode = "";
// give the shipper id field focus
document.addEventListener("change", function() {
let hasFocus = document.querySelector("input[name=shippernumber]");
hasFocus.focus();
});
}
},
sendFocus: function(e) {
document.addEventListener("keydown", function(e) {
var input = e.target.nodeName.toLowerCase() === "input";
var form = e.target.form;
if (e.key === "Enter" && input) {
var index = Array.prototype.indexOf.call(form, e.target);
form.elements[index + 1].focus();
}
});
}
},
created() {
let that = this;
this.fetchBatches().then(function() {
that.sendFocus();
});
}
Я прокомментировал столько, сколько мог. Метод addApplication
- это метод, который проверяет, является ли штрих-код числом или AddToBatch . Если это числовой штрих-код, вставьте его в массив, поскольку он распознается как обычный формат штрих-кода. Если он читает AddToBatch , затем очистите массив (который позже поместит массив в API), очистите поле отслеживания и отправьте курсор в поле отслеживания, чтобы прочитать новый номер отслеживания
Любая помощь будет очень признательна. Я единственный здесь в этом конкретном наборе навыков, и это отстой :( Спасибо
PS Нет jQuery. ES6 желательно.