0
votes

I have a Knockout model , which I display in table using the foreach binding. I have an edit button in each row and when I click the edit button I like to display the data on to the input fields and I want to edit it there, which should update back the knockout model.

I have a sample jsFiddle here and I am struggling to bind the selected row to input fields using knockout.

Please guide me to bind the selected row to the input fields.

HTML Code:

<div>
<div>
    <table>
        <th>Name</th>
        <th>Age</th>
        <th>Country</th>
        <tbody data-bind="foreach: players">
            <tr>
                <td data-bind="text: name"></td>
                <td data-bind="text: age"></td>
                <td data-bind="text: country"></td>
                <td>
                    <button data-bind="click: $root.editPlayers">Edit</button>
                </td>
            </tr>
        </tbody>
    </table>
</div>
<div>
    <h3>Edit</h3>
    Name:
    <input type="text" data-bind="value: name" />
    <br/>Age:
    <input type="text" data-bind="value: age" />
    <br/>Country:
    <input type="text" data-bind="value: country" />
    <br/>Tropies:
    <select data-bind="options: trophies, optionsText: 'Select Trophy'"></select>
</div>

JavaScript

    var player = function (name, age, country) {
    this.name = ko.observable(name);
    this.age = ko.observable(age);
    this.country = ko.observable(country);
    this.trophies = ko.observableArray['AO','US'];
};

var playerModel = function () {
    var self = this;
    self.players = [
    new player('Roger', 32, 'swiss'),
    new player('Stan', 28, 'swiss')];

    self.trophies = ['AO','US','FO', 'WB'];

    self.editPlayers = function (data) {
        console.log(data.name());
    }

}

ko.applyBindings(new playerModel());
1

1 Answers

0
votes

Your problem was not in the player list but in your edit player - you need to bind that to an object, such as 'editPlayer' and set the current player to that player on clicking the edit button.

http://jsfiddle.net/LCFua/2/

<div data-bind="with: editPlayer">
    <h3>Edit</h3>
    Name:
    <input type="text" data-bind="value: name" />
    <br/>Age:
    <input type="text" data-bind="value: age" />
    <br/>Country:
    <input type="text" data-bind="value: country" />
    <br/>Tropies:
    <select data-bind="options: trophies, optionsText: 'Select Trophy'"></select>
</div>

Use the with binding to bind that div to the editPlayer. Also if you want to use a multi-select to select multiple trophies you need to make some changes to your select list.