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

maaz picture maaz · Jul 26, 2012 · Viewed 13.2k times · Source

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?

Answer

aiolos picture aiolos · Jul 27, 2012

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.