Reputation: 44275
This code does a search and displays the results. I want to conditionally disable input
s.I am using knockout to control when an input
is disabled.
Requirement:
input
is disabled when set by the system. In the following code input that comes from readDatabase()
works well. If the user types in the Hometown/Nickname input
then tabs out then input
disables. How can I fix this code to meet the second requirment?
Update
I am not opposed to getting some help from jQuery. I do not want to throw out my view model binding entirely.
HTML
Name: <input type="text" data-bind="value: userInput, valueUpdate: 'input'" /><br />
Hometown: <input type="text" data-bind="value: Hometown, disable: Hometown" /><br />
NickName: <input type="text" data-bind="value: Address, disable: Address" />
JavaScript
function MyViewModel() {
var self = this;
self.userInput = ko.observable();
self.Hometown = ko.observable();
self.Address = ko.observable();
self.userInput.subscribe(function () {
readDatabase(self);
});
}
ko.applyBindings(new MyViewModel());
function readDatabase(self){
if(self.userInput().substring(0,1) == "a"){
self.Hometown("A town");
self.Address("A address");
}
else {
self.Hometown("");
self.Address("Other address");
}
}
Upvotes: 1
Views: 82
Reputation: 10328
You could use an extender to provide a flag indicating where the data came from:
ko.extenders.isServerSet = function (target, value) {
target.isServerSet = ko.observable(value);
return target;
};
function MyViewModel() {
var self = this;
self.userInput = ko.observable();
self.Hometown = ko.observable().extend({
isServerSet: false
});;
self.Address = ko.observable().extend({
isServerSet: false
});;
self.userInput.subscribe(function () {
readDatabase(self);
});
}
ko.applyBindings(new MyViewModel());
function readDatabase(self) {
if (self.userInput().substring(0, 1) == "a") {
// don't overwrite user-provided values
if (!self.Hometown()) {
self.Hometown("A town");
self.Hometown.isServerSet(true);
}
if (!self.Address()) {
self.Address("A address");
self.Address.isServerSet(true);
}
} else {
self.Hometown("");
self.Address("Other address");
}
}
Name: <input type="text" data-bind="value: userInput, valueUpdate: 'input'" /><br />
Hometown: <input type="text" data-bind="value: Hometown, disable: Hometown.isServerSet" /><br />
NickName: <input type="text" data-bind="value: Address, disable: Address.isServerSet" />
Upvotes: 3