JavaScript closure, just not getting it -
i'm trying add inputs iteratively, , able run calculation independently on each, can not seem apply closure principles. calculation function working on last item added. i've tried using loop within around main function (addit()) seems make things worse... here's basic html:
<button class="btn btn-default btn-block" onclick="addit('item'+count)">add one</button> <form> <div id="itemform"></div> <form>
and here overly complex , inelegant js (by way, i'm open better ways of doing this, please don't hesitate jump on this):
count = 0; addit = function(p) { count++; var itfrm = document.getelementbyid("itemform"); var itdiv = document.createelement("div"); var children = itfrm.children.length + 1 itdiv.setattribute("id", "itemdiv") itdiv.appendchild(document.createtextnode(p)); itfrm.appendchild(itdiv); var remove = document.createelement("a"); var linktext = document.createtextnode("remove it"); remove.setattribute("href", "#"); remove.setattribute("onclick", "removeit()"); remove.appendchild(linktext); var brk = document.createelement("br"); var num = document.createelement("input"); num.setattribute("id", "numinput"+count); num.setattribute("type", "number"); num.oninput = function () { var numinput = document.getelementbyid('numinput'+count).value ; var divisor = 10; var result = document.getelementbyid('result'+count); var myresult = (number(numinput) / number(divisor)); result.value = myresult; }; num.setattribute("placeholder", "set number..."); var clc = document.createelement("input"); clc.setattribute("id", "result"+count); clc.setattribute("readonly", "readonly"); clc.setattribute("placeholder", "after calculation..."); var hr = document.createelement("hr"); itdiv.appendchild(remove); itdiv.appendchild(num); itdiv.insertbefore(brk, num); itdiv.appendchild(clc); itdiv.appendchild(hr); }; function removeit(elem) { var elem = document.getelementbyid('itemdiv'); elem.parentnode.removechild(elem); return false; };
i tried setup jsfiddle here reason removeit function doesn't work there, although it's working locally me, removes oldest iteration. thoughts on how i've botched welcomed , appreciated well.
var countstring = count.tostring(); num.oninput = function() { var numinput = document.getelementbyid('numinput' + countstring).value; var divisor = 10; var result = document.getelementbyid('result' + countstring); var myresult = (number(numinput) / number(divisor)); result.value = myresult; };
it scoping issue count. global variable closure it. use local variable gets re declared on each button press fix it.
Comments
Post a Comment