JSFiddle - React, Tailwind, and code Playground
by tuanhnt1712
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>All posts</h2>
<div class="content">
<div class="float-left">
<ul id="update-posts" data-bind="foreach: posts">
<li>
<div>
<div class="item">Post ID</div> <span data-bind="text: $data.id"></span>
</div>
<div>
<div class="item">Title</div>
<input type="text" style="width: 1500px;" data-bind="value: $data.title"/>
</div>
<div>
<div class="item">Body</div>
<input type="text" style="width: 1500px;" data-bind="value: $data.body"/>
</div>
<div>
<div class="item">User Id</div>
<input type="text" style="width: 1500px;" data-bind="value: $data.userId"/>
</div>
<div>
<input type="button" value="Update" data-bind="click: $root.update"/>
<input type="button" value="Delete Item" data-bind="click: $root.remove"/>
</div>
</li>
</ul>
</div>
</div>
JavaScript
function ProductsViewModel() {
var self = this;
self.posts = ko.observableArray();
var baseUri = "https://jsonplaceholder.typicode.com/posts";
self.create = function (formElement) {
// If valid, post the serialized form data to the web api
$(formElement).validate();
if ($(formElement).valid()) {
$.post(baseUri, $(formElement).serialize(), null, "json")
.done(function (o) { self.posts.push(o); });
}
}
self.update = function (post) {
$.ajax({ type: "PUT", url: baseUri + '/' + post.id, data: post });
}
self.remove = function (post) {
// First remove from the server, then from the UI
$.ajax({ type: "DELETE", url: baseUri + '/' + post.id })
.done(function () { self.posts.remove(post); });
}
$.getJSON(baseUri, self.posts);
}
$(document).ready(function () {
ko.applyBindings(new ProductsViewModel());
})