I want to dynamically create a button that will drop a key from an object. At this point however I am simply using an alert to test for the correct value that will be later passed to the function that will drop the key. I am running a for-in loop in and I am trying to pass the iterator to a function called in the loop. The problem is that the alert statement is using the iterator 'i' and as the loop ends all instances of this alert have been changed to the final value of 'i'. (I hope that makes sense!)
locations = {};
function Location(nickname, address) {
this.nickname = nickname;
this.address = address;
}
Location.prototype.showLocations = function() {
var x=document.getElementById("demo");
output = "<table><tr><th>Location</th><th>Address</th><th>Delete</th></tr>";
for (i in locations) (function(i)
{
output+=listThis(i);
}) (i);
// for (i in locations) {
// output+=listThis(i);
// }
output+="</table>"
x.innerHTML=output;
}
function listThis(i){
thisLoc = locations[i].nickname;
var thisOutput="<tr><td>"+locations[thisLoc].nickname+"</td><td>"+locations[thisLoc].address+"</td><td><input type='button' value='X' onclick='alert(locations[thisLoc].nickname)' /></td></tr>";
return thisOutput;
}
function enterLocation() {
var address = document.getElementById('address').value;
var nickname = document.getElementById('nickname').value;
locations[nickname] = new Location(nickname, address);
locations[nickname].showLocations();
}
The markup is:
<p id="demo">Table to go in here.</p>
<div id="panel">
<input id="nickname" type="textbox" placeholder="Location Name" />
<input id="address" type="textbox" placeholder="Sydney, NSW" />
<input type="button" value="Enter" onclick="enterLocation()" />
</div>
Please note that I have tried to work with the info found at this post Javascript - how to work with the iterator in a for loop with callbacks but have not succeeded. You will see another for loop commented out that I was trying initially.
thisLoc, noti.