MVC Spring Model - dynamically accessing attribute list index
-
17-06-2021 - |
Question
I have a question regarding how to access an index from a model attribute list dynamically. In my code, I have some javascript which is reading a value from a model. The model has an attribute which is potentially a list.
document.getElementById("phoneNumberRPhone").value = "${model.people[index].phoneNumber.number}";
Here, you can see that I'm trying to set a javascript value to a number retrieved from a model where I can have multiple people. Index is my dynamic value. It works fine if I specifically state model.people[0] or model.people[1], but if I try to set a number to index and use index dynamically, it no longer works.
I would be very grateful for any help anyone could provide on this. I'm certain it's either just a matter of user error or improper use of syntax.
Solution
Apparently ${index}
doesn't exist at all in the JSP/EL scope at the point JSP/EL has to print that piece of JS code. It would only work of you're doing for example (although this approach is highly questionable):
<c:forEach items="${model.people}" varStatus="loop">
document.getElementById("phoneNumberRPhone").value = "${model.people[loop.index].phoneNumber.number}";
</c:forEach>
Keep however in mind that JSP is merely a HTML code generator and that JavaScript is part of it. JSP and JavaScript doesn't run in sync. Rightclick page in webbrowser and do View Source to see it.