2

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 ?

2
  • 3
    Please add the final javascript. If there are no customers, there will be no values[0]. View source and paste it here as well.
    – Gunslinger
    Commented Aug 2, 2013 at 8:59
  • Check if you actually have ${customer.name}
    – Alex
    Commented Aug 4, 2013 at 11:55

3 Answers 3

2

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>
0

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>
0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.