问题
I have this <g:select>
in a .gsp
file. But unlike any ordinary <g:select>
's this one would have the attribute disabled=""
if a certain condition is met.
Following the code:
<g:select name="test"
from="${["foo1","foo2"]}"
<g:if test="${true}">disabled=""</g:if> />
It returned an error: Grails tag [g:select] was not closed
But when I change it into this:
<g:select name="test"
from="${["mu1","mu2","mu3"]}"
${ if(true) { println "disabled=\"\"" } }/>
It returned this error: Attribute value must be quoted.
Both of the error message are under the exception, org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException
The question is how could we make this work? Is there a possible answer without using a custom TagLib?
回答1:
The GSP form field tags treat disabled
as a boolean property, so you can say
<g:select .... disabled="${true}" />
Generally you should be able to use any expression under the usual Groovy-truth rules but I believe it makes a special case for the strings "true" and "false" (the latter would normally be considered true
under Groovy-truth rules as a non-empty string). If in doubt you can always say
disabled="${(someExpression) as boolean}"
回答2:
No need to use the println, try this
<g:select .... ${(conditional)?"disabled":""} ... />
回答3:
<g:select disabled="${true}"...
is fine but when you submit and it is a required field the value will not be submitted so use this jQuery code to enable the field when pressing the submit button
$(function() {
$('form').on('submit', function() {
$(this).find(':disabled').removeAttr('disabled');
});
});
来源:https://stackoverflow.com/questions/12507918/grails-gif-in-gselect