I have an interactive widget that I want to display on my page. However I also want to give the user the possibility to generate more instances of the same widget and to be able to interact with them simultaneously. As an example, let's say this is my widget:
<div id="my_widget">
<script type="text/javascript" src="jquery-1.5.1.js"></script>
<script>
$(document).ready(function() {
$("#up_one").click(function() {
$("#number").val(parseInt($("#number").val())+1);
});
});
</script>
<p>
<input type="submit" id="up_one" value="Up One!"/>
<input type="text" id="number" type="number" value="0" maxlength="2">
</p>
</body>
Now, to display this on my main page I use load(), as follows
$(document).ready(function() {
var i = 0;
$("#hello_submit").click(function() {
$("#hello_div").load("widget_test.html");
});
});
</script>
<div id="hello_div">
<p>
<input id="hello_submit" type="submit" value="New counter" />
</p>
</div>
But there are 2 problems with this. First I can only load the widget once, and second, it would allow the user to navigate directly to widget_test.html, which would defeat the purpose of all this. So I tried another method that involves turning the widget into a long string. To this string I add an index parameter which is used to dynamically generate id and class names, like this:
function BAString(){
this.getBas = function(value){
var bas = '<body><script>$(document).ready(function() {$("#up_one'+value+'").click(function() {\
$("#number'+value+'").val(parseInt($("#number'+value+'").val())+1);});}); </script> <p>\
<input type="submit" id="up_one'+value+'" value="Up One!"/>\
<input type="text" id="number'+value+'" type="number" value="0" maxlength="2"></p></body>';
return bas;
};
In my main page I then use this function:
$(document).ready(function() {
var i = 0;
$("#hello_submit").click(function() {
var b = new BAString();
$("#hello_div").append(b.getBas(i));
i++;
});
});
This second method seems to work great but I can see obvious problems with maintainability as my widget becomes more and more complex. So what is the ideal solution to be used in a case like this?