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. Commented Aug 2, 2013 at 8:59
  • Check if you actually have ${customer.name} 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>
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.