简体   繁体   中英

submitting checkboxes with Thymeleaf + SpringBoot

I have a SpringBoot app. with this thymelaf template, that works fine when submitting:

 <div class="form-group required-control">
                                    <label for="gre">GRE</label>
                                    <input id="gre" type="checkbox" name="gre" th:checked="*{gre}" th:onclick="submit()"   />

                                </div>

but when I add another checkbox, It always take in account the first one, regardless which one I click

 <div class="form-group required-control">
                                    <label for="gre">GRE</label>
                                    <input id="gre" type="checkbox" name="gre" th:checked="*{gre}" th:onclick="submit()"   />

 <label for="gre2">GRE2</label>
                                    <input id="gre2" type="checkbox" name="gre2" th:checked="*{gre2}" th:onclick="submit()"   />


                                </div>

There is no technical problem here. I think there is a problem with your submit() function, because I created a normal form and tried your same instance, and all selection combinations worked correctly.

I am adding the entity, controller and html files respectively for example.

public class Example {

    private boolean gre;
    private boolean gre2;

    public Example() {
    }

    // getter/setter ...
}
@Controller
@RequestMapping("/example")
public class ExampleController {

    @GetMapping("/create")
    public String createExample(Model model) {
        model.addAttribute("example", new Example());
        return "example-form";
    }

    @PostMapping("/insert")
    public String insertExample(Model model, Example example) {
        model.addAttribute("example", example);
        return "example-form";
    }
}
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<div>
    <form action="/example/insert" method="post" th:object="${example}">
        <div class="form-group required-control">
            <label for="gre">GRE</label>
            <input id="gre" type="checkbox" name="gre" th:checked="*{gre}" />
            <label for="gre2">GRE 2</label>
            <input id="gre2" type="checkbox" name="gre2" th:checked="*{gre2}" />
        </div>
        <button type="submit">Submit Form</button>
    </form>
</div>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM