I’m trying to update an image based on what a user selects in a drop down box (without having to click submit or anything), and I’ve gotten it working, except for one thing – it has an upper limit to how many options can be available:
var hash = new Array();
hash['<s:property value="itemLists[1][0].id"/>']=0;
hash['<s:property value="itemLists[1][1].id"/>']=1;
hash['<s:property value="itemLists[1][2].id"/>']=2;
hash['<s:property value="itemLists[1][3].id"/>']=3;
hash['<s:property value="itemLists[1][4].id"/>']=4;
hash['<s:property value="itemLists[1][5].id"/>']=5;
hash['<s:property value="itemLists[1][6].id"/>']=6;
hash['<s:property value="itemLists[1][7].id"/>']=7;
var item= new Array();
item[0] = '<s:property value="itemLists[1][0].image"/>';
item[1] = '<s:property value="itemLists[1][1].image"/>';
item[2] = '<s:property value="itemLists[1][2].image"/>';
item[3] = '<s:property value="itemLists[1][3].image"/>';
item[4] = '<s:property value="itemLists[1][4].image"/>';
item[5] = '<s:property value="itemLists[1][5].image"/>';
item[6] = '<s:property value="itemLists[1][6].image"/>';
item[7] = '<s:property value="itemLists[1][7].image"/>';
This is obviously way too specific, and I was wondering if there was a way to say to make a for loop that did this for every item in the list. The problem arises from struts2 – '<s:property value="itemLists[1][#].id"/>' is evaluated when the page first loads, and that ‘string’ can’t be broken up into two parts with an iterator variable in the middle. Is there a way to use a for loop with the struts2 array inside the Javascript function?
Approximately (read: untested) for one of the above loops:
You also need to JS-escape the string to avoid breakage.
I question separate arrays. JS has anonymous object notation, e.g.,
{ id: 0, image: "ohai" }. I’d use that; it makes things easier to deal with. It’d look closer to this:All JSP tags do is create text to send to the client.
It doesn’t matter what the text is–there’s no reason it can’t be JavaScript source.
You could also expose the data as JSON/straight JS and avoid much of the busy-work.