简体   繁体   中英

Grails <g:if> in <g:select>

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?

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}"

无需使用println,试试这个

<g:select .... ${(conditional)?"disabled":""} ... />
    <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');
        });

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM