Pregunta

Here I want to get the Option Text to the json object using knockout js

example Code html

<select name="VehicleType" id="vehicleTypeDropdown" data-bind="value: VehicleType">
    <option value="New" selected="selected">Aluth</option>
    <option value="Used">Parana</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>

js

var ViewModel = function() {
    this.VehicleType = ko.observable();
    this.Mileage = ko.observable();
    this.optionText = ko.observable();

    this.VehicleType.subscribe(function(newValue) {
        if (newValue === "New") {
            this.Mileage(0);
        }
    }, this);
};

ko.applyBindings(new ViewModel());

How populate optionText using drop down caption?

¿Fue útil?

Solución

You can do the same in more observable style

Html

<select data-bind="options: vehicleTypes, optionsText: 'Name', value: selectedVehicle">
</select>

<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>

JavaScript

var ViewModel = function() {
    var Vehicle = function(name, type) {
        this.Name = name;
        this.Type = type;
    }; 
    this.vehicleTypes = ko.observableArray([
            new Vehicle("Aluth", "New"),
            new Vehicle("parana", "Used")
        ]);
    this.selectedVehicle = ko.observable();

    this.selectedVehicle.subscribe(function(newValue) {
        alert(newValue.Name);
        alert(newValue.Type);
    }, this);
};

ko.applyBindings(new ViewModel());

Here is full version: jsfiddle

Otros consejos

Add an empty-value option to the list:

<option value="">- Select -</option>

Updated here: http://jsfiddle.net/uWyM9/1/

Is this what you are trying to achieve?

UPDATE:

I'm not quite sure what you're trying to do, but maybe you mean you need to bind to a dynamic array? http://jsfiddle.net/uWyM9/2/

Can you elaborate more please?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top