I have a html form for adding multiple addresses:
http://i48.tinypic.com/jg2ruo.png
This way If I change the Address Type selection the entire form has to bind to the correct json address object:
var jsonAddresses = { Addresses:
[
{ AddressType: 1, Address1: "", Address2: "",Province:"",City:"",State:"",PostalCode:"",Municipal:"" },
{ AddressType: 2, Address1: "", Address2: "",Province:"",City:"",State:"",PostalCode:"",Municipal:"" },
{ AddressType: 3, Address1: "", Address2: "",Province:"",City:"",State:"",PostalCode:"",Municipal:"" },
{ AddressType: 4, Address1: "", Address2: "",Province:"",City:"",State:"",PostalCode:"",Municipal:"" }
]
};
I have done this with Jquery with a lot of code actually but I want to know how can I do this with Knockout. The idea is instead of having a fixed json object with the 4 types of addresses i want to have only 1 json object and if I select an address type that is not in the array then the object is added and binded, if the address type already exists in the array then just bind it. then i can have a “remove” link that when clicked the selected address type object is removed from the array.
Thanks in advance.
I’m guessing a little bit on this, because its not entirely clear. You want a single form for editing addresses, with a dropdown that lets you select which address you are editing. I’ve put a working fiddle together, but here are the important parts.
You have a concept of an
Addressobject, which is observable since you will be updating the values. Then you need a viewmodel to keep track of all the address, have some concepted of theselectedaddress, and the ability to add new addresses. This is the part that wasn’t clear, so I just went with aNew Addressbutton. Let me know if you have something else in mind. Other than the list of states, and the initial address data (both which should come from the server) this is all the code, and as you can see knockout makes it pretty simple.HTML:
ViewModels:
EDIT1: added remove button. This is for the demo, obviously you will want some safety logic when the array is empty.