Viktor Pizhun
Viktor Pizhun

Reputation: 33

Problem with th:each in <select> HTML tag. Thymeleaf and Spring

So I've made this simple project in Intellij idea. I'm filling array with next elements:

public class formClass {
    private String list[] = {"+", "-", "x", "/"};
    public String[] getList() {
       return list;
    }
}

This is controller section. Here i'm adding formClass object as a model attribute:

@Controller    
public class GreetingController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String greeting(@RequestParam(name="name", required = true, defaultValue = "null") String name, Model model){
        model.addAttribute("name", name);
        model.addAttribute("form_class", new formClass());
        return "greeting";
    }

}

greeting.html

<form id="form1" action="#" th:action="@{/}" th:object="${form_class}" method="POST">
    <select th:field="*{list}" class="formable">
        <option th:each="i : *{list}" th:value="${i}" th:text="${i}"></option>
    </select>
</form>

everything works fine, except that all options are marked with selected attribute therefore the last item is automatically selected, which i try to avoid and can't figure out where i'm going wrong

enter image description here

i'll be glad for any help, thank you!

Upvotes: 0

Views: 695

Answers (2)

Viktor Pizhun
Viktor Pizhun

Reputation: 33

solution was the simplest, i just removed th:field from select tag and set th:selected to the '+' option as Laminoo Lawrance recommended enter image description here

enter image description here

Upvotes: 0

Laminoo Lawrance
Laminoo Lawrance

Reputation: 425

Try th:selected for selecting default option.

Please use below syntax

<option th:each="i : ${list}" th:value="${i}" th:text="${i}" th:selected="${ i==\"+\"" }></option>

Hope this will work.

Upvotes: 1

Related Questions