Error in selected-at and sort functions


I have a problems if anyone can help!
I’m trying to use the selected-at function in hidden value, but it always shows me an error message

I have text question called ‘address’ then followed by hidden value ‘select_text’ with the statement in it says:
selected-at( #form/address , 2)
but when testing it gives me the following error message “Calculation Error: Error in calculation for /data/select_text Attempting to select element 2 of a list with only 0 elements.”
I feel I’m missing something obvious but I could not find what is!!

I having a similar problem with sort function in hidden value caled ‘sort_text’
I have in the hidden value: sort(#form/list_of_names, true())
but it is giving me this error: "Calculation Error: Error in calculation for /data/sort_text Called sort() on empty list with args org.javarosa.xpath.XPathLazyNodeset@45d8fccd

anyone can help or explain what is going wrong please!


This issue is a bit tricky. Essentially, the issue is that calculations are evaluated right away and updated as the data changes. This means that before you fill out #form/address, it is empty, so the function attempts to evaluate that selected_at expression on an empty value.

The solution is to only attempt to evaluate that expression if you know it will succeed. For instance, the expression selected-at(#form/address , 2) will fail if there are fewer than two words. You can then write the expression as

if(count-selected(#form/address) >= 2, selected-at(#form/address , 2), "")

This way the expression will return an empty string rather than fail, as the selected-at portion is only evaluated when there are enough arguments.

1 Like

Thank you @Ethan_Soergel , your suggestion worked perfectly. much appreciated!