2016-09-30 52 views
1

最近我開始學習前端開發,所以如果這個問題太愚蠢不要感到驚訝。 我想要做的是綁定文本框來選擇文本,而不是它的ID。這是一個jsfiddle:https://jsfiddle.net/1rtzfLr1/敲除綁定文本框來選擇文本

這裏是我的HTML:

<div data-bind="foreach: objects()"> 
    <input type="text" data-bind="value: type" /> 
    <button type="button" data-bind="click: $parent.removeObject">-</button> 
</div> 
<div> 
    <select data-bind="options: types, optionsValue: 'id', optionsText: 'title', optionsCaption: 'Type...', value: itemToAdd().type"></select> 
    <button id="create-object-button" type="button" data-bind="click: addObject">+</button> 
</div> 

和JS:

function model() { 
    var self = this; 

    self.objects = ko.observableArray(); 
    self.types = ko.observableArray([new Type(1, 'one'), new Type(2, 'two'), new Type(3, 'three')]); 
    self.itemToAdd = ko.observable(new Object()); 

    self.addObject = function() { 
    self.objects.push(self.itemToAdd()); 
    self.itemToAdd(new Object()); 
    }; 

    self.removeObject = function(object) { 
    self.objects.remove(object); 
    }; 

    function Object(type) { 
    var self = this; 
    self.type = type; 
    } 

    function Type(id, title) { 
    var self = this; 
    self.id = id; 
    self.title = title; 
    } 
}; 

ko.applyBindings(new model()); 

的事情是,我要顯示two而不是2在文本框,但在同一時間,這是一個部分應該提交併在表單提交的表單我想提交2值,因爲在實際應用中它是java枚舉名稱。

謝謝並抱歉,如果它的問題太混亂。

回答

0

對不起,你沒有積極的後果,但也許是這樣的?
http://jsfiddle.net/LkqTU/31963/

JS

function type(id, title) { 
    var self = this; 
    self.id = ko.observable(id); 
    self.title = ko.observable(title); 
}; 

var initialArray = [ 
    new type(1, 'one'), 
    new type(2, 'two'), 
    new type(3, 'three') 
] 


function model() { 
    var self = this; 

    self.types = ko.observableArray(initialArray); 
    self.options = ko.observableArray(initialArray); 
    self.selectedtype = ko.observable(''); 
    self.removeObject = function(p) { 
    self.types.remove(p); 
    } 
    self.addObject = function() { 
    self.types.push(new type(
     self.selectedtype().id(), 
     self.selectedtype().title())); 
    } 
} 

var mymodel = new model(); 

$(document).ready(function() { 
    ko.applyBindings(mymodel); 
}); 

HTML

<div data-bind="foreach: types"> 
    <p> 
    <span data-bind="text: id"></span>: 
    <input type="text" data-bind="value: title" /> 
    <button data-bind="click: $parent.removeObject"> 
    </p> 

    - 
    </button> 

</div> 
<br/> 
<select data-bind="options: options, 
         optionsText: 'title', 
         value: selectedtype, 
         optionsCaption: 'Choose...'"></select> 
<button data-bind="click: addObject">+</button> 

</button>