Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
153
rated 0 times [  155] [ 2]  / answers: 1 / hits: 11720  / 11 Years ago, tue, january 28, 2014, 12:00:00

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/


More From » jquery

 Answers
13

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 />

[#48270] Monday, January 27, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlyn

Total Points: 421
Total Questions: 73
Total Answers: 100

Location: South Georgia
Member since Sat, Jul 25, 2020
4 Years ago
;