Use if/else within textfield?

2.3k views Asked by At

I have already found several ways to use if / else tags and also how to use it within a <tr> tag.

But is it possible to use it within a <s:textfield> tag ?

I want to disable several fields (textfields and datepicker) if a certain parameter is true. At the moment, I have the whole code twice. Once with disable="true"and once without. This makes the jsp extremely verbose.

I would be very happy if there were a better/shorter way.

2

There are 2 answers

1
Predrag Maric On BEST ANSWER

Try with this expression inside <s:textfield>

disabled="%{myCondition}"

where myCondition should evaluate to true or false.

0
Andrea Ligios On

There are many solutions to this problem, each one fitting it better according to the number of tags, the cleanest/shortest code ratio desired, etc...

For example, you can

  1. set a variable and use it in your textfields:

    <s:set var="disabled" value="%{condition}"/>
    <s:textfield ... disabled="%{#disabled}" />
    
  2. use an action method that returns a boolean, as in @PredragMaric answer:

    public boolean getConditionFromAction(){
        return (foo!=bar);
    }
    
    <s:textfield ... disabled="%{conditionFromAction}" />
    
  3. create two JSP snippets and include them (overkill in case of just disabled, but helpful in other cases, like showing a complete different set of fields)

    <s:if test="%{condition}">
        <s:include page="snippetA.jsp" />
    </s:if>
    <s:else>
        <s:include page="snippetB.jsp" />
    </s:else>
    

    (in which case, remember to put

    <%@ taglib prefix="s" uri="/struts-tags" %>
    

    in the snippets too).

  4. disabling them with javascript on page loading (example with jQuery):

    <script>
        $(function(){
            <s:if test="%{condition}">
                $("input[type='text']").attr('disabled','disabled');
            </s:if>
            <s:else>
                $("input[type='text']").removeAttr('disabled');
            </s:else>
        });
    </script>
    

    (better using a class selector ovbiously).

Regarding your latest comment:

I want to disable the fields if a certain condition is true to make further edits impossible.

remember that you MUST perform the controls server side, because every user is able to alter the HTML / DOM (with Firebug, or FF DevTools, Chrome DevTools etc...) or simply forging a request ad-hoc without even visiting your page, and enabling the fields you have disabled.

Client side validation is user friendly and appreciated as a first filter, server side one is mandatory.