Now make it a Madlib Module (to include it in larger projects).
Look at the object generators:
function Madlib_item(type, index) {
// members
this.index = index;
this.text = "";
this.value = "";
//initialization
if (type=="noun") {
this.text = "Please type a noun";
} else if (type=="adjective") {
this.text = "Please type an adjective";
}
//methods
this.input = function() {
return this.text + ': <input type="text" id="choice' + this.index + '" />/<br/>';
}
}
function Madlib_form(items, action) {
// members
this.items = items;
this.items_count = items.length;
this.html = '';
//initialization
this.html = '<form action="' + action + '" method="post">';
//methods
this.present = function() {
return_str = this.html;
for (i=0; i<this.items_count; i++) {
return_str += items[i].input();
}
return_str += "</form>";
return return_str;
}
}
function Madlib_story(text, choices, substitution_string) {
// members
this.story = "";
this.substitution_string = substitution_string;
this.choices_count = choices.length;
//initialization
this.story = text;
//methods
this.getStory = function() {
var text = this.story;
for (i=0; i<this.choices_count; i++) {
text = text.replace(this.substitution_string, document.getElementById("choice" + i).value);
}
return text;
}
this.getChoices = function() {
return_str="";
for (i=0; i<this.choices_count; i++) {
return_str += document.getElementById("choice" + i);
return_str += ", ";
}
return return_str;
}
}