Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

My jsp code is

 <% List selected = (List) session.getAttribute("clist");

   JSONArray arr = new JSONArray();
    JSONObject tmp;

    for (int i = 0; i < selected.size(); i++) {
        tmp = new JSONObject();
        tmp.put("Id", selected.get(i));

        arr.put(tmp);
    }%>

and i am using hidden field to pass this array to javascript

  <input type='hidden' id="agencycontactid" name="agencycontactid" value="<%=(null != arr) ? arr : ""%>" />

here arr gives value arr=[{"Id":"9"},{"Id":"11"}]

My javascript code is

  var s=$('#agencycontactid').val(); alert(s);

But alert gives only [{

Please help me

Thanks

share|improve this question
    
Change type hidden to text to see if it shows correct json value. I am sure the issue is there. – gaurav Nov 7 '14 at 9:11
    
@gaurav You are absolutely right.Please tell me how to set that arr value to hidden field – user100 Nov 7 '14 at 9:15
    
Your input tag looks like this: <input ... value="[{"Id":...> so the value attribute is only [{ due to the " in the string you're trying to pass – icke Nov 7 '14 at 9:15
    
@icke how to overcome this problem – user100 Nov 7 '14 at 9:25
    
See my answer below, I hope it helps. – icke Nov 7 '14 at 9:28
up vote 0 down vote accepted

change value attr from

value="<%=(null != arr) ? arr : ""%>"

to

value='<%=(null != arr) ? arr : ""%>'
share|improve this answer
    
it not working it gives error Uncaught SyntaxError: Unexpected end of input – user100 Nov 7 '14 at 9:25

The variable arr from your scriptlet is passed to the HTML as a string with the content [{"Id":"9"},{"Id":"11"}], so your input tag will look like this: <input type='hidden' id="agencycontactid" name="agencycontactid" value="[{"Id":"9"},{"Id":"11"}]" />. So the value attribute will only contain the part of the string up to the first ", i.e. [{.

You could try to put the json data in a place where " doesn't interfere with the HTML, like inside a hidden tag like so

<div id="jsondata">
    <%=arr%>
</div>

or put the scriptlet inside a <script> tag:

<script type="text/javascript">
    var s = <%=arr%>;
</script>

Changing the delimiters of the value attribute to ' instead of " would also work but would break as soon as your json data contains strings with ' in them. However if you are sure that will never be the case, that is by far the easiest fix.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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