I want to introduce a simple notation to bind a HTML <input>
element to a JavaScript object. Something like:
<script>
var qform = {
uid : "",
pass : ""
};
</script>
<form method="get" action="#">
<input id="temp0" type="text" name="uid" bind="qform.uid" />
<input id="temp1" type="password" name="pass" bind="qform.pass" />
<input type="submit" value="submit" />
</form>
So that any changes to the <input>
s will change my JS variable. The way I'm trying to implement it is:
<script>
var x = 0;
for(x = 0; x < 2; x++) {
var inputField = document.getElementById("temp" + x);
var bindObj = inputField.getAttribute("bind");
var bindObjTree = bindObj.split(".");
var parent = window;
for (var i = 0; i < bindObjTree.length - 1; i++) {
parent = parent[bindObjTree[i]];
}
child = bindObjTree[bindObjTree.length - 1];
inputField.value = parent[child];
inputField.onchange = function() {
var xp = parent;
var xc = child;
xp[xc] = inputField.value;
alert(JSON.stringify(window["qform"]));
};
} // for
</script>
However only the second input field behaves the way I want to. Can someone explain why that is? I'm guessing it has something to do with closures. I'm really trying to understand what I'm doing wrong rather than find a solution (I can easily work around this with JQuery, but I don't really want that).