grailsgrails-3.1

How can I do: required="false" in grails g:select?


required="false" does not work in "g:select" tag


Example:

<g:select from="${}" name="select" required="false" />

and

<g:select from="${}" name="select" required="true" />

produces a html tag required (in html5)


How can I make the "g:select" produces the required or not, dynamically?


Solution

  • Just remove required, for eg:

    <g:select id="select" from="${}" name="select"/>
    

    You can use jquery to change the g:select to be required or not required. For example, lets say you have another

    <g:select id="yesNo" from="[yes, no]">
    

    In the gsp, use javascript:

    $( "#yesNo" ).change(function() {
      if($(this)[0].value == "yes") {
         $( "#select" ).attr('required', 'required')
      }
      else {
         $( "#select" ).removeProp( "required" )
      }
    });
    

    Another approach is if you pass a variable required to gsp, you can use <g:if>:

    In controller:

    [required: "true"] //If dont want required, simply don't return required at all
    

    In gsp:

    <g:if test="${required}">
       <g:select from="${}" name="select" required/>
    </g:if>
    <g:else>
       <g:select from="${}" name="select"/>
    </g:else>