【问题标题】:submitting checkboxes with Thymeleaf + SpringBoot使用 Thymeleaf + SpringBoot 提交复选框
【发布时间】:2020-12-27 09:34:11
【问题描述】:

我有一个 SpringBoot 应用程序。使用这个 thymelaf 模板,提交时效果很好:

 <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>

但是当我添加另一个复选框时,它总是考虑第一个,无论我点击哪个

 <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>

【问题讨论】:

    标签: java spring spring-boot spring-mvc thymeleaf


    【解决方案1】:

    这里没有技术问题。我认为您的 submit() 函数存在问题,因为我创建了一个普通表单并尝试了您的相同实例,并且所有选择组合都正常工作。

    例如,我分别添加了实体、控制器和 html 文件。

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-10
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      • 2021-04-08
      • 2014-06-26
      • 1970-01-01
      相关资源
      最近更新 更多