Pracede
Pracede

Reputation: 4371

How to make a JSTL foreach loop in javascript code?

I am working on a JSP page. I use Spring framework, JSTL and Jquery. I mix some js code and JSTL code. Here is the code :

This is my Spring controller:

Contract contract = services.getContractInfo(contractNumber);
contract.addCustomer(customer);
model.addAttribute("contract", contract);

This is my Java script:

<script language="javascript">
    $(document).ready(function(){
        var values = new Array();
        <c:forEach var="customer" items="${contract.customers}" varStatus="status">
            values.push("${customer.name}");   
        </c:forEach>

        alert(" VALUES => "+values[0]);
        ....
    });
</script>

Alert shows me "VALUES => undefined".

I don't understand. What's happen ?

Upvotes: 2

Views: 21165

Answers (3)

Beniton Fernando
Beniton Fernando

Reputation: 1533

This code you have provide should work perfect. The only possiblity values[0]= undefined is due the ${contract.customers} might be empty. The below code should help to find if the collection is empty

<script language="javascript">
    $(function(){
        var values = new Array();
        <c:if test="${empty contract.customers}">
           values.push("No customers Found"); 
        </c:if>         
        <c:forEach var="customer" items="${contract.customers}" varStatus="status">
            values.push("${customer.name}");   
        </c:forEach>
        alert(" VALUES => "+values[0]);

    });
</script>

Upvotes: 2

heshik nandan
heshik nandan

Reputation: 21

You cant use a JSTL inside a script function. try putting the value outside the script function

<c:forEach var="customer" items="${contract.customers}" varStatus="status">
values.push("${customer.name}");   
</c:forEach>

just use this to show the values of assign it some textbox or table.

Upvotes: 0

Ayub Malik
Ayub Malik

Reputation: 2578

I don't think you need the document ready (in this specific case). Also try setting the type of script rather than language. I assume you have a getCustomers() method in Contract class that returns a Collection.

e.g.

<script type="text/javascript">
    var values = [];
    <c:forEach var="customer" items="${contract.customers}" varStatus="status">
        values.push("${customer.name}"); 
    </c:forEach>
    alert(" VALUES => " + values[0]);
</script>

Upvotes: 0

Related Questions