3

I am creating an user registration form using jsp,in which there is an option to select State from a combo box.I am using a simple html combo box but i am receiving State as a json object from web service.So how to populate the combo box with json object.

State Json is as follows,

{"States":[{"id":"1","stateName":"Alabama","code":"AL"},
{"id":"4","stateName":"Arkansas","code":"AR"},
{"id":"8","stateName":"Delaware","code":"DE"}]}

My Javascript function is,

function getStates(){    
url = WSPath;
response=initiateRequest(url);}

My HTML combo box is <select name="State">

I need to populate the combo-box with the above json object.

2
  • A combobox is a combination of a drop down menu and a text input (hence the name). A select element won't generate one. Commented Apr 9, 2012 at 12:25
  • 1
    Don't do this with JavaScript, it's inefficient and less reliable than plain (on the client) HTML. Do it with JSP, and cache the results. Commented Apr 9, 2012 at 12:28

1 Answer 1

5

Pure js:

var select = document.createElement("select");
var obj = JSON.parse(response);

for (var i=0; i < obj.States.length; i++)
{
  var option = document.createElement("option");
  option.id = obj.States[i].id;
  option.value = obj.States[i].code;
  option.innerHTML = obj.States[i].stateName;
  select.appendChild(option);
}

Tweak the id, value and innerHTML to your needs.

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

6 Comments

Hi Thanks for your reply.I did tried as you mentioned but i received an error at var obj = JSON.parse(response);
What is the error? I don't know how you're reading the json. I was assuming that response contains the json string. If it's already parsed then you don't need that call to JSON.parse.
"states" is useless you need the array with objects inside.
@B.F. I don't get your point, obj.States is an array of objects
@mihai Your code is ok! I wonder why there is the "States" key with one array item in the JSON.
|

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.