Reputation: 2618
I'm trying to set the selected
option's attribute with thymeleaf + springMVC as shown below:
(item.codItem
and defaultCodItem
are Long)
<select id="selItems">
<th:block th:each="item : ${myItems}">
<option value="564" th:value="${item.codItem}" th:selected="(${item.codItem} eq ${defaultCodItem})? 'selected' : '' "
th:text="${item.codItem} + ' || ' + ${defaultCodItem}"> 564 || ?
</option>
</th:block>
</select>
But the result is...
<select id="selItems">
<option selected="selected" value="455">11/2014 - 455 || 450</option>
<option selected="selected" value="450">450 || 450</option>
<option selected="selected" value="452">452 || 450</option>
<option selected="selected" value="457">457 || 450</option>
<option selected="selected" value="453">453 || 450</option>
<option selected="selected" value="454">454 || 450</option>
<option selected="selected" value="451">451 || 450</option>
</select>
When I expected this:
<select id="selItems">
<option selected="" value="455">11/2014 - 455 || 450</option>
<option selected="selected" value="450">450 || 450</option>
<option selected="" value="452">452 || 450</option>
<option selected="" value="457">457 || 450</option>
<option selected="" value="453">453 || 450</option>
<option selected="" value="454">454 || 450</option>
<option selected="" value="451">451 || 450</option>
</select>
So, how should I compare item.codItem
with defaultCodItem
in the template to set selected
attribute correctly?
Upvotes: 2
Views: 8075
Reputation: 2071
According to Thymeleaf documentation :
The Standard Dialect includes attributes that allow you to set these attributes by evaluating a condition, so that if evaluated to true, the attribute will be set to its fixed value, and if evaluated to false, the attribute will not be set
selected is one of them . I think you should write the condition simply as :
th:selected="${item.codItem} eq ${defaultCodItem}"
I guess your current line does not work as expected because non null values are evaluated to true (such as your empty string)
Upvotes: 8