johnnyg24 Posted January 22, 2010 Share Posted January 22, 2010 I'm trying to allow the user to load in different data sets based on what buttons they click. <input type='button' id='promo1' value='1086' onclick='getPromo(this.value);' /><input type='button' id='promo2' value='1087' onclick='getPromo(this.value);' /> var tmp_1086 = "item1,item2,item3"var tmp_1087 = "item1,item3,item3"function getPromo(data){var promoData = tmp_+data.split(",")//then do something with the array} Can anyone tell me why this doesn't work. If a user were to pick 'promo1' all I get back is "tmp_1086". Link to comment Share on other sites More sharing options...
Greywacke Posted January 22, 2010 Share Posted January 22, 2010 try evaluating that object to return the array like follows: var tmp_1086 = "item1,item2,item3"var tmp_1087 = "item1,item3,item3"function getPromo(data){var promoData = eval("tmp_"+data.split(","));//then do something with the array} Link to comment Share on other sites More sharing options...
justsomeguy Posted January 22, 2010 Share Posted January 22, 2010 Operations go from right-to-left. When you write this:tmp_+data.split(",")First it looks for a variable called data, and it splits it. Since data is something like "1086", splitting it on a comma will return an array with a single element ("1086"). Then, you're trying to concatenate that onto the end of a variable called "tmp_". So that line is the same as doing this:var ar = data.split(",");var promoData = tmp_ + ar;It would be best to store your data in an array or object and then access it by key name. e.g.: var pData = { '1086': 'item1,item2,item3', '1087': 'item1,item3,item3'};function getPromo(data){ var promoData = pData[data].split(","); //then do something with the array} Link to comment Share on other sites More sharing options...
johnnyg24 Posted January 22, 2010 Author Share Posted January 22, 2010 Thanks to both of you. Each method worked. I went with justsomeguy's response. Link to comment Share on other sites More sharing options...
Greywacke Posted January 22, 2010 Share Posted January 22, 2010 sure, his way is actually the better approach.i usually tackle problems where they appear though, not so much at the root. Link to comment Share on other sites More sharing options...
ShadowMage Posted January 22, 2010 Share Posted January 22, 2010 sure, his way is actually the better approach.i usually tackle problems where they appear though, not so much at the root.But if you fix it at the root you won't have to fix it in 50 different places later. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.