Old time OO programmer, new to javascript/html coding.
So I'm playing around with JavaScript "classes", trying to make a reusable unit that writes itself into the html.
<html>
<script>
function Foo(min_input, max_input) {
var n_min_input = min_input;
var n_input = max_input;
var curr_shown = min_input;
this.show_one_more = function () {
if (curr_shown < n_input) {
document.getElementById('input' + curr_shown).style = 'display: block';
curr_shown++;
}
}
this.show_one_less = function () {
if (curr_shown > n_min_input) {
curr_shown--;
document.getElementById('input' + curr_shown).style = 'display: none';
}
}
this.write_inputs = function () {
for (var i = 0; i < n_min_input; i++) {
document.write("<input type='text' style='display: block' value='" + i + "' id='input" + i + "' name='input" + i + "'/>");
}
for (var i = n_min_input; i < n_input; i++) {
document.write("<input type='text' style='display: none' value='" + i + "' id='input" + i + "' name='input" + i + "'/>");
}
//want to essentially do this, but don't know how
document.write("<p><input type='button' onclick='this.show_one_more()' value='+'></input><input type='button' value='-' onclick='this.show_one_less()'/></p>");
}
}
var f = new Foo(1, 5);
f.write_inputs();
//works here, but would rather it be generated in f.write_inputs();
document.write("<p><input type='button' onclick='this.show_one_more()' value='+'></input><input type='button' value='-' onclick='this.show_one_less()'/></p>");
</script>
<input type="button" value="stuff" id="sbutton"/>
</html>
So basically, i want to get some sort of closure with this in the document write call on the button. I feel like this is a pattern people may have used in the past (but I could be totally wrong). My ideas:
make a global variable var foo_idx=0
and an array var allfoos = [];
. In the initialize (body of the class) do this.foo_idx=foo_idx; allfoos[foo_idx]=this;foo_idx++
and then I can use allfoos[foo_idx]
to capture this. BUT that feels hacky. How do people typically create reusable html elements?