Hi i am working on a form using knockout js i have to perform CRUD operation. Out of these i am able to do all except update(edit). I want on click of edit same form will open as open on click on addperson but with the values of person. here is my code
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="knockout-3.1.0.js"></script>
</head>
<body>
<a href="#" data-bind="click:addFields">ADDPerson</a>
<a href="#" data-bind="click:resetPerson">Reset</a>
<div data-bind="foreach:fields,visible:show">
<div data-bind="text:firstName"></div>
<div data-bind="text:lastName"></div>
<a href="#" data-bind="click:$root.remove">Remove</a>
<a href="#" data-bind="click:$root.edit" >edit</a>
</div>
<form data-bind="visible:showfields">
First Name:
<input data-bind="value:formFirstName"/>
Last Name:
<input data-bind="value:formLastName"/>
<a href="#" data-bind="click:addPerson">ADD</a>
</form>
<body>
<script>
function person(firstName, lastName) {
var self = this;
self.firstName = ko.observable(firstName);
self.lastName = ko.observable(lastName);
}
function personForm(formFirstName, formFirstName) {
var self = this;
self.formFirstName = ko.observable("david");
self.formLastName = ko.observable("rock");
}
function personViewModel() {
var self = this;
self.formFirstName = ko.observable("add");
self.formLastName = ko.observable("Value");
self.show = ko.observable(true);
self.showfields = ko.observable(false);
self.fields = ko.observableArray([
new person("paul", "kerry"),
new person("john", "cena")
]);
self.addFields = function() {
self.show(false);
self.showfields(true);
};
self.addPerson = function() {
self.fields.push(new person(self.formFirstName(), self.formLastName()));
self.show(true);
self.showfields(false);
}
self.resetPerson = function() {
self.fields.removeAll();
self.fields.push(new person("john", "cena"));
self.fields.push(new person("abc", "def"));
}
self.remove = function(person) {
self.fields.remove(person);
}
}
ko.applyBindings(new personViewModel());
</script>
</html>
Here's how you can update existing model :
Create new observable :
Create new function for edit :
Wire up HTML :
Why create new observable? -
Answer - All the edits you make will be updated in realtime, you won't have to hit UPDATE like button :-)
I hope that clears..
Updated demo with single form : http://jsfiddle.net/rahulrulez/7f7hsj8w/2/
If you want to edit the form in place. Kind of like asp.net webform style.
The simple way is to has the input disabled initially. Then have the edit button to enable the inputs. Hope this helps.
Here is a complete solution. i have made some modifications.
View
Model
Fiddle Demo