0

I have seleconeradio, for example:

<h:selectOneRadio value="#{myBean.selectedValue}" layout="pageDirection">
    <f:selectItems value="#{myBean.myList}" var="a" itemValue="#{a}" itemLabel="#{a}"/>
</h:selectOneRadio>

where myList is list of integers, e.g. 1,3,2,4. If user selects second element (i.e. 3) I want in myBean selectedValue to be 2, so I want to get index of selectItems item.

What should I write in f:selectItems itemValue tag? Or it is impossible?

P.S. I can do it by creating a new class in which I have the index property and create a new list of that class, giving the right index. But it is very bad solution.

Kuba
  • 2,069
  • 23
  • 30
Aram Gevorgyan
  • 2,175
  • 7
  • 37
  • 57
  • You have `selectedValue` setup after selection. You can check which item in your list has that value. Position in list is index which you looking for. – Vasil Lukach May 05 '14 at 21:02
  • But can't I know directly index of item in selectItems ? – Aram Gevorgyan May 05 '14 at 21:05
  • Why? You have the name and the value. That's all you need. You need to be free to reorder them, add to them, delete them, in the GUI without having to adjust your code as well. – user207421 May 06 '14 at 05:13
  • @EJP: Sorry, I don't understand you well. The naame and the value isn't all I need. I need to know index – Aram Gevorgyan May 07 '14 at 09:01

2 Answers2

6

You can actually use c:forEach for this case. This is especially usefull when you have to deal with a collection containing duplicates and therefore can't use indexOf() for example.

<h:selectOneRadio value="#{myBean.selectedValue}" layout="pageDirection">
  <c:forEach items="#{myBean.myList}" var="a" varStatus="idx">
    <f:selectItem itemValue="#{idx.index}" itemLabel="#{a}"/>
  </c:forEach>
</h:selectOneRadio>

Just be sure to include the JSP JSTL Core namespace if you haven't done yet.

xmlns:c="http://xmlns.jcp.org/jsp/jstl/core

DanielK
  • 424
  • 6
  • 17
0

you should use indexOf(Object o) .. it returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element... your code should probably look like this..

int index  = myList.indexof(selectedValue);