Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change observable value on dropdown change Knockout Js

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.

like image 261
Overmachine Avatar asked Oct 01 '12 16:10

Overmachine


People also ask

How do I set observable value in knockout?

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.

What is Ko observable ()?

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.

What is two way binding in knockout JS?

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.


1 Answers

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());
like image 197
RP Niemeyer Avatar answered Oct 22 '22 14:10

RP Niemeyer