I would use some MV* library for this kind of task.
Maybe you have a look at Backbone. A small library (about 7k in production) with lots of nice functionality for those kinds of tasks.
1) You have models
representing you data as a proper javascript object.
Each model is instantiated with:
var MyModel = Backbone.Model.extend({});
var instance = new MyModel();
You could use defaults:
var MyModel = Backbone.Model.extend({
defaults: { name: 'Freddy Krueger', age: 0, child: '' }
});
Models have events to which you could subscribe. Most used is the "change" event. So you could bind a function to a general change by just declaring
model.on("change", function(){});
Or if you want to watch a specific attribute to change
model.on("change:name", function(){});
Of course you could "trigger" custom events
model.trigger("outOfOrder");
2) You could use views
to render the different forms
View = Backbone.View.extend({
el: $("#placeToRender"),
render:function(){
$(this.el).html(yourMagicHTML);
}
});
Even better: you have microtemplating on board, which means:
You could define HTML including placeholders within a script-tag
<script type="text/template" id="#maintemplate">
<div>
<%= content %>
</div>
</script>
That wouldn't be rendered by your browser, but you could get its content by
$("#maintemplate").html()
So that your view could render itself easily with:
View = Backbone.View.extend({
el: $("#main"),
template:_template($("#maintemplate").html()),
render:function(){
$(this.el).html(template(this.model.toJSON()));
}
});
Where
this.model.toJSON()
is in fact a model with a key called "content" (e.g. {content:"blah!"}), which is used to render the template,
so that <%= content %> is substituted with the actual content.
And many more stuff to discover.
Referring to your problem - you could abstract your problem with backbone like the following:
Every tab you need to display is a view to which belongs a template to determine its html as well as a model, which represents the content of the tab.
You could embed each tab in another view, such that you have one embracing view to control the whole tabbing system and nesting views, which represent each individual tab.
You could write a custom show() method to show an individual tab and a method which coordinates which of the tabs is shown and which should be hidden.
So instead of doing the annoying work yourself, it may be a good idea to use a library to help.
Some places to start (besides the official API and documentation):
http://backbonetutorials.com/
http://ricostacruz.com/backbone-patterns/
http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/
http://addyosmani.github.io/backbone-fundamentals/