Get value from selected Table row Knockout.js
javascript, jquery, knockout.js
Solution
Here's an example of how you could do it:
http://jsfiddle.net/qWmat/3/
function MyVM(data) {
var self = this;
self.items = ko.observableArray(data.map(function (i) {
return new rowModel(i.id, i.name, i.status);
}));
self.select = function(item) {
self.selected(item);
};
self.selected = ko.observable(self.items()[0]);
}
And you bind your textboxes to the properties in the `selected` property:
<input type="text" name="ID" data-bind="value: selected().ID" disabled/>
And you bind the click handler in your `tr` like so:
<tr data-bind="click: $parent.select">
Updated to include enable binding (http://jsfiddle.net/qWmat/8/). Add a property for whether or not to edit:
self.enableEdit = ko.observable(false);
Then update your `select` function to turn it to true:
self.select = function(item) {
self.selected(item);
self.enableEdit(true);
};
If / when you save or cancel you could the set it back to false if you want.
Update your bindings on the input boxes:
<input type="text" name="Status" data-bind="value: selected().Status, enable: enableEdit" />
Problem
I need a little help. I have created a table that gets values from JSON response, but for this example lets create a hardcoded html table like following: ``` <table id="devtable"> <tr> <th>ID</th> <th>Name</th> <th>Status</th> </tr> <tr> <td>001</td> <td>Jhon</td> <td>Single</td> </tr> <tr> <td>002</td> <td>Mike</td> <td>Married</td> </tr> <tr> <td>003</td> <td>Marrie</td> <td>Complicated</td> </tr> </table> ID : <input type="text" name="ID" data-bind="value: ID" disabled/> <br> Name : <input type="text" name="Name" data-bind="value: Name" disabled/> <br> Status : <input type="text" name="Status" data-bind="value: Status" disabled/> <br> <input type="button" value="Send" disabled/> ``` Requirement is: when I select a row of table, values of columns goes to the input boxes and enable button as well. As I am trying to learn Knockout.js by doing this exercise. I think I have to make a viewmodel like this: ``` var rowModel = function (id, name, status) { this.ID = ko.observable(id); this.Name = ko.observable(name); this.Status = ko.observable(status); } ``` Link of project is here: http://jsfiddle.net/qWmat/