【问题标题】:Set default value of select in thymeleaf在百里香中设置选择的默认值
【发布时间】:2019-02-26 17:23:05
【问题描述】:

我正在使用 Spring boot + thymeleaf,我正在尝试设置选择元素的默认值,以显示存储在数据库中的选定对象(编辑表单)。

为此,我从控制器中将实体及其值插入到模型中,但是,当我尝试设置选择的默认值时,它总是获得第一个选项。

这是代码:

    <select class="selectpicker"
        id="alarmPeriod" name="alarmPeriod"                                                     
        th:selected="${alarm.alarmPeriod}" 
        th:value="${alarm.alarmPeriod}"> 

        <option th:each="period:${periods}" 
            th:value="${period}" th:text="${period}">
        </option></select>

我尝试过使用th:field="*{alarm.alarmPeriod}",但百里香处理器崩溃了。

如何使用存储的实体值设置选择的默认值?

PD:alarm是我的实体,alarmPeriod是alarm的一个属性。

【问题讨论】:

  • 您必须在选项上添加th:selected,而不是在选择上
  • @ayrton 只显示选择的最后一个选项,但它不是我要显示的存储值。
  • 您想将正确的选项标记为选中,对吧?然后,您应该将 th:selected 添加到选项中,表达式的计算结果为真或假,具体取决于您的 alarmPeriod
  • @ayrton,这行得通!非常感谢。

标签: java html spring-boot thymeleaf


【解决方案1】:

selectedoption 标记的属性。由于您尝试将其中一个选项标记为选中,因此您必须将 th:selected 属性添加到您的选项中,其表达式将根据您的 alarmPeriod 计算为 truefalse

【讨论】:

    【解决方案2】:

    选择的选项应该像使用 htnl 选择标记一样作为选项放置,下面的代码应该可以工作

        <select class="selectpicker"
        id="alarmPeriod" name="alarmPeriod"> 
        <option value="${alarm.alarmPeriod}" selected="selected">
             ${alarm.alarmPeriod} 
        </option>
    
        <option th:each="period:${periods}" 
            th:value="${period}" th:text="${period}">
        </option></select>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-14
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 2014-11-19
      相关资源
      最近更新 更多