I have this dropdown which have options if vehicle is new or used.
<select name="VehicleType" id="vehicleTypeDropdown" data-bind="value: VehicleType">
<option value="New" selected="selected">Nuevo</option>
<option value="Used">Usado</option>
</select> `
And this input:
<input type="text" name="Mileage" data-bind="disable: VehicleType() === 'New',value: Mileage" class="input-large"> `
If the value in the dropdown selected is New the input must be disabled, and if used the input should be enabled, but if I enter a value the observable will grab this value and if I change the dropdown value to new the observable must become zero.
To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.
An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted. The main advantage of KO is that it updates our UI automatically when the view model changes.
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.
A manual subscription in your view model is a good way to handle something like this. The subscription might look like:
this.VehicleType.subscribe(function(newValue) {
if (newValue === "New") {
this.Mileage(0);
}
}, this);
Here is a sample using it: http://jsfiddle.net/rniemeyer/h4cKC/
The HTML:
<select name="VehicleType" id="vehicleTypeDropdown" data-bind="value: VehicleType">
<option value="New" selected="selected">Nuevo</option>
<option value="Used">Usado</option>
</select>
<input type="text" name="Mileage" data-bind="disable: VehicleType() === 'New', value: Mileage" class="input-large">
<hr/>
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
The JS:
var ViewModel = function() {
this.VehicleType = ko.observable();
this.Mileage = ko.observable();
this.VehicleType.subscribe(function(newValue) {
if (newValue === "New") {
this.Mileage(0);
}
}, this);
};
ko.applyBindings(new ViewModel());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With