I have a table of data that is an observable of observables in KO. When you tab out of the last input of the last row, it adds an additional row of inputs so you can type in new data. It is supposed to initially put the focus in the first input. When that input is blurred, it runs some checks. If any of those checks fail, I want to show a message(currently working) and sent the focus back to that input. I cannot figure out how to get that focus back.
Here is the relevant HTML snippet:
<tbody data-bind="foreach: items">
<tr>
<td>
<div data-bind="if: (itemNo.length < 1)"><input data-bind="value: itemNo, hasFocus: $parent.invalidItem, event: { blur: $parent.checkItemNo }, attr: { name: 'brochureitems[' + $index() + '].itemNo', id: 'brochureItems_' + $index() + '__itemNo' }, validationOptions: { errorElementClass: 'input-validation-error' }" class="form-control item-id" /></div>
And here is my Knockout code:
var itemsModel = function(items) {
var self = this;
self.items = ko.observableArray(items);
self.invalidItem = ko.observable(true);
self.checkItemNo = function(data) {
self.invalidItem(false);
console.log(data);
var itemNo = $.trim(data.itemNo());
if (itemNo != "") {
var item = "";
$.each(window.listOfItems, function(i, v) {
if (v.No.search(itemNo) != -1) {
item = v.Description;
return;
}
});
if(item != "") {
var match = ko.utils.arrayFirst(self.items, function(item) {
return itemNo === item.itemNo;
});
if (!match) {
data.itemDesc(item);
}
} else { // invalid item #
slideDownMsg("Invalid item number.");
slideUpMsg(3000);
self.invalidItem(true);
}
}
}
self.submit = function() {
//self.showErrors(true);
if (viewModel.errors().length === 0) {
console.log('Thank you.');
$("#brochureForm").submit();
}
else {
console.log('Please check your submission.');
viewModel.errors.showAllMessages();
$(".input-validation-error").first().focus();
}
}
self.addLine = function() {
self.items.push( new itemModel() );
};
self.insertLine = function(index) {
self.items.splice(index, 0, new itemModel() );
};
self.removeItem = function(item) {
self.items.remove(item);
};
self.errors = ko.validation.group(self.items, { deep: true, live: true });
self.validate = function() {
self.errors.showAllMessages();
}
};
Obviously, I left a lot of code out, but hopefully this is enough to show my issue.