I’m creating a form where the user needs to add form elements dynamically. addEmptyItem() accomplishes this by cloning the first item in the given list, clearing its values, updating its indices, and appending it.
Of course, it requires that there is at least one list item in the list. My solution is to always display the first list item, and then iterate over the rest. This is bothering me due to the code duplication. It gets worse when the list items contain a lot of fields.
What I want is something similar to a do-while loop. Any suggestions how to solve this problem without duplicating code like I’m doing now:
<s:submit type="button" onclick="addEmptyItem($('#owners')); return false;"
value="%{getText('ownership.addOwner')}"/>
<ul id="owners">
<li>
<s:textfield name="ownership.owner[0].name"
label="%{getText('ownership.owner.name')}"/>
<s:textfield name="ownership.owner[0].share"
label="%{getText('ownership.owner.share')}"/>
</li>
<s:iterator value="ownership.owner" status="i" begin="1">
<li>
<s:textfield name="ownership.owner[%{#i.count}].name"
label="%{getText('ownership.owner.name')}"/>
<s:textfield name="ownership.owner[%{#i.count}].share"
label="%{getText('ownership.owner.share')}"/>
</li>
</s:iterator>
</ul>
You could try to move code with fields to new page file and include it with like this:
and use index param in included file.