0

I need to bind a java.util.List<String> to a HTML drop-down javascript.

I am able to get the java.util.List in the below format:

[Name1,Name2,Name3]

For binding I will use this code (it works fine):

var opt = document.createElement("OPTION");                 
opt.text = xhr.responseText;
opt.value = xhr.responseText;
document.getElementById("slctFullName").options.add(opt); 

But I don't know the easiest approach to iterate through these elements.

Please let me know how to iterate through the elements :(

Thanks,

6
  • What technologies are you using? JSP, Freemarker? If you're passing data directly into the stream consider JSON. Commented Feb 16, 2013 at 13:32
  • yes. JSP, servlet and javascript. For sending the request in servlet, I use xmlHttpRequest. In servlet, I am creating the list and sending the list using: resp.getWriter().print(nameList); I am able to retrieve the list in the format I mentioned in the above post, but not able to iterate through it properly. Please let me know if you want me to post some more of the code. Commented Feb 16, 2013 at 13:37
  • 1
    You need to send valid JSON over the wire, so something like ["Name1", "Name2", "Name3] (notice the quotes), you can then parse then JSON and you have a javascript array. Commented Feb 16, 2013 at 13:49
  • Ok, I did a quick change to get the same in JSON like: {"Name1":"Name1","Name2":"Name2","Name3":"Name3"}. I am able to get this in javascript. Now tell how to bind this JSON with the drop-down in javascript. I used Gson in java servlet to generate this JSon. Thanks, Commented Feb 16, 2013 at 13:52
  • 1
    So, now you need to parse that to a javascript object as per the link and then loop over it as in here and build your options... Commented Feb 16, 2013 at 14:12

1 Answer 1

1

You first need to get the List into a javascript-friendly format, I would suggest:

["Name1", "Name2", "Name3"] 

This represents a javascript array in JSON, now you should be able to assign what to a javascript object by parsing it

var arr = JSON.parse(xhr.responseText);

Now you can loop over it like a normal array:

for (var i=0; i<arr.length; ++i) {
 var opt = document.createElement("OPTION");                 
 opt.text = arr[i];
 opt.value = arr[i];
 document.getElementById("slctFullName").options.add(opt); 
}

Note the compatability caveats in here.

Sign up to request clarification or add additional context in comments.

2 Comments

var arr = JSON.parse(xhr.responseText); is not working in IE. Getting a javascript error: JSON is undefined. Please let me know how to make this work in IE :(
Check the link. You can use eval but it's not too safe...

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.