tags:

views:

28

answers:

1

hey

so im using javascript, jqeury, and html here. basically i have a dynamic number of buttons that are being created, and will each call a function using unique variables. the variables are held in a json variable. here is the code as it is:

    var box = "<font size=\"2\">The following assassins are in your current location:<br/><table width = \"100%\">";

    for (var i=0; i<info.length; i++) {
        if(userid != info[i].playerid){
            box += "<tr><td>"+info[i].name+" | rank: "+info[i].rank+"</td><td align=\"right\"><input id='attack' type='button' onclick='loadAttack(userid, info[i].playerid, info[i].name, info[i].rank, location)' value='Attack'/></td></tr>";
        }    
    }
    box += "</table></font>";

    $("#assassinBox").html(box);        

the box looks fine, with the proper names, ranks, and buttons. the problem is when a button is pushed, info is undefined. i think this is because the button doesnt get its own copy of i, and i is out of the bounds of the array at the end of the loop. im struggling to think of a solution, some way of passing the onclick function a unique variable?

thanks!

+2  A: 
box += "<tr><td>"+info[i].name+" | rank: "+info[i].rank+"</td><td align=\"right\"><input id='attack' type='button' onclick='loadAttack(userid, info["+i+"].playerid, info["+i+"].name, info["+i+"].rank, location)' value='Attack'/></td></tr>";

That should work. Although if I were you I would consider rewriting it to not use inline event handlers and maybe building the HTML with jQuery or the native DOMElement creation methods rather than concatenating strings of HTML. It makes it a lot more maintainable in the long run.

CD Sanchez
hmm i am still getting info is undefined in firebug when the button is pressed. perhaps the info variable is not in the domain where the button is pressed, making it undefined?
meres
i made info a global variable and it works now, thanks
meres