Thymeleaf - How to add checked attribute to input conditionally

后端 未结 5 535
滥情空心
滥情空心 2020-12-08 07:18

As you know, input component has an attribute, checked to whether mark the checkbox as enabled by default or not.



        
相关标签:
5条回答
  • 2020-12-08 07:42

    You can conditionally add checked attribute to radio input in thymeleaf as below:

     <input type="radio" th:checked="${sales.sales_head.sales_type} == CREDIT" class="sales_type" value="CREDIT"  name="sales_type" >
    

    Here if sales_type is CREDIT the radio will be checked. Otherwise it remains unchecked.

    0 讨论(0)
  • 2020-12-08 07:48

    According to the official thymeleaf documentation

    http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#fixed-value-boolean-attributes

    th:checked is considered as a fixed-value Boolean attribute.

    <input type="checkbox" name="active" th:checked="${user.active}" />
    

    Where user.active should be a boolean.

    So in your case it should be as Andrea mentioned,

    <input type="checkbox" name="mycheckbox" th:checked="${flag}" />
    
    0 讨论(0)
  • 2020-12-08 07:53

    After digging a little, I found out the solution. There is th:checked attribute for that purpose.

    This works:

    <input type="checkbox" name="mycheckbox" th:checked="${flag} ? 'checked'">
    

    This fails:

    <input type="checkbox" name="mycheckbox" th:checked="${flag} ? 'checked' : ''">
    

    If checked="" is set to input component, it's marked checked. This method is valid for custom attributesth:attr also. Consider following example:

    <p th:attr="customattr=${flag}?'attr'></p>
    

    If flag is true, it's replaced with:

    <p customattr="attr"></p>
    

    If flag is false, it's replaced with:

    <p></p>
    
    0 讨论(0)
  • 2020-12-08 07:56

    I faced problem for showing checkbox (tick mark on/off) in thymeleaf based on true or false value for the property. I solved it by following way.

    Method in controller

    @RequestMapping(value = "/test")
    public String showCheckbox(Model model) {
     boolean myBooleanVariable = false;
     model.addAttribute("myBooleanVariable", myBooleanVariable);
     return "sample-checkbox";
    }
    

    In HTML page:

    <input type="checkbox" name="myBooleanVariable" th:checked="${myBooleanVariable}"/>
    
    0 讨论(0)
  • 2020-12-08 08:03

    Neither suggested solutions worked for me.

    This one worked:

    th:checked="${#strings.equals(param.myRequestParameterXYZ, 'foobar')}"
    
    0 讨论(0)
提交回复
热议问题