0

I am trying to create an arraylist with three dates. I then want to save the arraylist into variable in a formatted way. However, when I try to document.write the variable, the elements are completely different.

<script>
<% List<String> strList = new ArrayList<String>();
strList.add("23-2-2016");
strList.add("24-2-2016");
strList.add("25-2-2016"); %>


var unavailableDates = [<% for (int i = 0; i < strList.size(); i++) { %><%= strList.get(i) %><%= i + 1 < strList.size() ? ",":"" %><% } %>];

document.write(unavailableDates);
</script>

The result I want is "23-2-2016", "24-2-2016", "25-2-2016".

However, I am getting this displayed: -1995,-1994,-1993

1
  • @NinaScholz The OP is generating javascript from a JSP, the dates are bing evaluated as expressions. Commented Feb 20, 2016 at 17:43

1 Answer 1

1

You need to use string literals when printing javascript, otherwise your dates will be treated as arithmetic expressions (23 - 2 - 2016 = -1995).

var unavailableDates = [
    <% for (int i = 0; i < strList.size(); i++) { %>
        '<%= strList.get(i) %>'
    //  ^                     ^
        <%= i + 1 < strList.size() ? ",":"" %>
    <% } %>
];
Sign up to request clarification or add additional context in comments.

7 Comments

I've tried this before but getting an error with everything between the two ' '. Error = Syntax error on token "'$tag_________________$tag__________________________________$tag_'", delete this token
Another error. "Syntax error on tokens, delete these tokens." It is pointing to every single quote.
@abcdefg Is it your IDE? if it is your IDE, just try to execute the JSP and see the output, for example eclipse's JSP editor is crap and sees errors everywhere
hahaha. You're right. I am using Eclipse but when I run, it displays. However, can I somehow add double quotes between each date. E.g. "23-2-2016", ...
@abcdefg Absolutely! Just change the single quotes to double quotes, it will work!
|

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.