Reputation: 1061
I am trying to enable the department select tag when the value of send to select tag is other than "global" using knockoutjs. But for some reason the department select tag is stuck to initial enable/disable state. Dynamical enable/disable works for other elements e.g. textarea
Select which determines the enable/disable state of the other
<select data-bind="options: recipientSelector, optionsText: 'name',value: selectedRecipient">
The select tag which needs to be disabled/enabled
<select data-bind="options: department_name"></select>
Javascrpt ViewModel
var SendMessageModel = function() {
var self = this;
this.to = ko.observableArray();
this.to_all = ko.observable();
this.title = ko.observable();
this.message = ko.observable();
this.recipientSelector = [
{ recipient: "global", name: "To All" },
{ recipient: "custom", name: "Custom" }
];
this.selectedRecipient = ko.observable();
this.department_name = ['CSE', 'ECE', 'EE'];
self.disableSelects = ko.pureComputed(function () {
return self.selectedRecipient().recipient == "global";
});
};
ko.applyBindings(new SendMessageModel());
Screenshot "Custom" option enables "Department" select element
Upvotes: 2
Views: 233
Reputation: 23397
You can use the enable
binding in combination with your selectedRecipient
observable like so:
var SendMessageModel = function() {
var self = this;
this.to = ko.observableArray();
this.to_all = ko.observable();
this.title = ko.observable();
this.message = ko.observable();
this.recipientSelector = [
{ recipient: "global", name: "To All" },
{ recipient: "custom", name: "Custom" }
];
this.selectedRecipient = ko.observable();
this.department_name = ['CSE', 'ECE', 'EE'];
self.disableSelects = ko.pureComputed(function () {
return self.selectedRecipient().recipient == "global";
});
};
ko.applyBindings(new SendMessageModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="
options: recipientSelector,
optionsText: 'name',
value: selectedRecipient"></select>
<select data-bind="
options: department_name,
enable: selectedRecipient().recipient === 'custom'"></select>
You could also use the visible
binding. This might still be a bit confusing since the second select
still kind of shows a default selection.
Upvotes: 1
Reputation: 5085
You can use enable
with the computed that's already in the view model:
<select data-bind="options: department_name, enable: disableSelects"></select>
See demo
This adds a disabled attribute to the select tag. How it looks visually will be dependent on your UI styles/framework.
Upvotes: 0