Grails -Gsp - How to make Check-box checked based on the value of the field

13,794

Solution 1

Use the checked attribute to control the state of your checkBox as described in the docs. Here you could add any expression to determine the state of the g:checkBox:

<g:message code="publicRuleInstance.course.label" default="Applied" />
<g:checkBox name="status " value="Applied" checked="${publicRuleInstance?.status == 'Applied'}"/>

<g:message code="publicRuleInstance.course.label" default="NotApplied" />
<g:checkBox name="status " value="NotApplied" checked="${publicRuleInstance?.status == 'NotApplied'}"/>

If you just want to allow one of the values - Applied or NotApplied a g:radioGroup would be the better choice. With a checkBox the user could choose both values Applied and NotApplied.

Solution 2

Value of checkBox should be boolean

<g:message code="publicRuleInstance.course.label" default="Applied" />
<g:checkBox name="status " value="${publicRuleInstance?.status =="Applied"}" />

<g:message code="publicRuleInstance.course.label" default="NotApplied" />
<g:checkBox name="status " value="${publicRuleInstance?.status == "NotApplied" }" />
Share:
13,794
maaz
Author by

maaz

Updated on July 07, 2022

Comments

  • maaz
    maaz almost 2 years

    I have a attribute called status in my domain which is String type can have any one of two values Applied , NotApplied

    I have two check boxes to input this value. in my edit page i want to display these two check box.

    If the value of status is Applied then the corresponding checkbox must be checked.

    my code

     <g:message code="publicRuleInstance.course.label" default="Applied" />
    <g:checkBox name="status " value="${publicRuleInstance?.status }" />
    
    <g:message code="publicRuleInstance.course.label" default="NotApplied" />
    <g:checkBox name="status " value="${publicRuleInstance?.status }" />
    

    but here both the checkboxes are checked.

    there must be a way to check the value i.e if the status = Applied then that perticular checkbox must be cheched else it should be unchecked.

    Is there any way to doing it?

  • maaz
    maaz almost 12 years
    Is there any hard code rule that saying checkBox should have boolean value?
  • aiolos
    aiolos over 11 years
    No - g:checkBox could have any value.
  • Aram Arabyan
    Aram Arabyan over 11 years
    It is logical that value of checkbox should be boolean. Other question is how groovy will parse value you pass. groovy.codehaus.org/Groovy+Truth
  • peveuve
    peveuve over 8 years
    checked attribute must be a boolean, but value attribute can be any value. See grails.github.io/grails-doc/3.0.x/ref/Tags/checkBox.html