2016-09-30 6 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 enum nameに提出したいと思います。

ご質問ありがとうございました。ご迷惑をおかけいたします。

答えて

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> 
関連する問題