JSFiddle - React, Tailwind, and code Playground
by stevehnh
HTML
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.0.js"></script>
<script src="http://jquery-json.googlecode.com/files/jquery.json-2.3.min.js"></script>
<script id='userRowTemplate' type='text/html'>
<tr>
<td class="id" data-bind='text: rowid'></td>
<td data-bind='text: userid'></td>
<td><span data-bind='text: userName, visible: !$parent.editing(), click: $parent.edit'></span><input id='inputName' type="text" data-bind='value: userName, visible: $parent.editing, hasfocus: $parent.editing' /></td>
</tr>
</script>
<div data-bind="visible: users().length > 0" id='results-list'>
<table>
<thead>
<th>ID</th><th>UID</th><th>Username</th>
</thead>
<tbody data-bind="template: { name: 'userRowTemplate', foreach: users }">
</tbody>
</table>
</div>
<input id="submit" type="button" value="Search" data-bind="click: doSearch" style="width: 60px" />
<input type="button" value="Save" data-bind="click: postBack, visible: editing()" />
CSS
/* Style the Table */
table {
border-collapse: collapse;
width: 100%;
}
table, th, td {
border: 1px solid #0E5280;
text-align: left;
}
th {
text-align: center;
}
td {
padding: 2px;
background-color: #A4D5FC;
color: black;
text-align: right;
}
td.id {
background-color: #FCFCCA;
color: black;
width: 55px;
text-align: center;
}
JavaScript
// return JSON with doSearch function
var data = {
json: $.toJSON({users: [{ rowid: "1", userid: "123", userName: "test1" }//, { rowid: "2", userid: "456", userName: "test2" }, { rowid: 3, userid: 789, userName: "test3" }
]
}),
delay: 0.1
}
var resultsModel = {
// Establish 'users' array to contain all the rows
users: ko.observableArray(),
editing: ko.observable(false).extend({ throttle: 400 }),
edit: function() { resultsModel.editing(true) },
// The search function used to pull back the JSON and push all rows to the 'users' array
doSearch: function() {
// Pulls the search term entered into the search field. Uses it as a value for the search.
var searchText = $('#text').val();
$.ajax({
url: "/echo/json/",
type: 'POST',
data: data,
context: this,
success: function(data) {
console.log(data);
// clear the users array on each search
resultsModel.users([]);
// iterate over each row of JSON. Push the row and the id's with it.
$.each(data, function() {
resultsModel.users.push({ rowid: ko.observable(data['users']['0']['rowid']), userid: ko.observable(data['users']['0']['userid']), userName: ko.observable(data['users']['0']['userName']) });
})
},
dataType: 'json'
});
},
postBack: function() {
var rawObject = ko.toJS(resultsModel.users);
var jsonData = JSON.stringify(rawObject);
$.ajax({
url: '/echo/json/',
type: 'POST',
data: jsonData,
success: function(data) {
console.log(jsonData);
resultsModel.editing(false);
},
error: function() {
resultsModel.editing(false);
}
});
}
};
ko.applyBindings(resultsModel);