Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check inputs with type checkbox with thymeleaf

I've been play around with spring-boot and thymeleaf; I'm trying to do a form where I will list numbers and the user will select them; however I would like to "checked" the third element (when equals 3) and I cannot see that the input is checked.

I don't have problems loading the information and display the checkboxes, the problem came when I want to check one of them by default when the page loads.

I need some help identifying what it should be the issue or if it is a bug with th:checked property.

I have this in the controller

@ModelAttribute("allFeatures")
public List<Integer> populateFeatures() {
    return  Arrays.asList(1, 2, 3, 4, 5, 6);
}

Here is the html code

<ul>
    <li th:each="feat : ${allFeatures}">
        <input type="checkbox" th:field="*{features}" th:value="${feat}" th:checked="${feat == 3}"></input>
        <label th:for="${#ids.prev('features')}" th:text="${'seedstarter.feature.' + feat}">Electric Heating</label>
    </li>
    <li th:remove="all">
        <input id="removed1" type="checkbox"/> <label for="removed1">Turf</label>
    </li>
</ul>

Thanks in advance.

like image 374
Rogelio Blanco Avatar asked Feb 10 '23 22:02

Rogelio Blanco


1 Answers

Use th:checked and avoid th:field and include 'name' attribute

<input type="checkbox" th:checked="${feat} == 3" name="features"></input>

Extra Comment

But the proper way will be to avoid th:checked and 'name' attributed and stick to the th:field. But in that case you have to make sure that you initialize the model attribute "features" in the controller before posting it to the view. Here you can define which checkbox to get checked by default from the controller itself.

But your situation seems a bit tricky as you want to display the dynamic list of checkboxes. So I prefer the first solution.

like image 179
Faraj Farook Avatar answered Feb 13 '23 22:02

Faraj Farook