Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSTL conditional check

Tags:

jsp

jstl

el

On my current page I am using JSTL to check if data is available for my form. Problem I am facing is "if there is no data I am not seeing the text fields either". I can solve it using and tags but that would entail lot of if else if else kind of code all through the page. Can anyone suggest me a better cleaner solution to this problem?

<c:if test="${salesData!=null}">
  <c:if test="${fn:length(salesBundle.salesArea) > 0}">
  <input type="text" id="sales_area" class="salesManagerStyle">
  </c:if>
</c:if>
like image 422
t0mcat Avatar asked Jun 02 '11 20:06

t0mcat


People also ask

How do you write if in JSTL?

The < c:if > tag is used for testing the condition and it display the body content, if the expression evaluated is true. It is a simple conditional tag which is used for evaluating the body content, if the supplied condition is true.

What is c if test?

C if StatementIf the test expression is evaluated to true, statements inside the body of if are executed. If the test expression is evaluated to false, statements inside the body of if are not executed.

What is the use of c if?

C has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

Can we use c if inside c when?

nested-if in C/C++Yes, both C and C++ allow us to nested if statements within if statements, i.e, we can place an if statement inside another if statement.


1 Answers

You can have multiple conditions in a test.

<c:if test="${salesData != null && fn:length(salesBundle.salesArea) > 0}">
    <input type="text" id="sales_area" class="salesManagerStyle">
</c:if>

But you can also use the empty keyword to do both a nullcheck and lengthcheck.

<c:if test="${not empty salesData.salesArea}">
    <input type="text" id="sales_area" class="salesManagerStyle">
</c:if>

That's the best what you can get, now. If you need to reuse the same condition elsewhere in the page, then you could also save it by <c:set>.

<c:set var="hasSalesData" value="${not empty salesData.salesArea}" />
...
<c:if test="${hasSalesData}">
    <input type="text" id="sales_area" class="salesManagerStyle">
</c:if>
...
<c:if test="${hasSalesData}">
    Foo
</c:if>
like image 126
BalusC Avatar answered Oct 26 '22 15:10

BalusC