socialMatrix
socialMatrix

Reputation: 1443

Populate HTML5 dropdown values with JSON data

I have US states JSON data as below

{"States":["Alaska","Alabama","Arkansas","American Samoa","Arizona","California","Colorado","Connecticut","District of Columbia","Delaware","Florida","Federated States of Micronesia","Georgia","Guam","Hawaii","Iowa","Idaho","Illinois","Indiana","Kansas","Kentucky","Louisiana","Massachusetts","Maryland","Maine","Marshall Islands","Michigan","Minnesota","Missouri","Northern Marianas","Mississippi","Montana","North Carolina","North Dakota","Nebraska","New Hampshire","New Jersey","New Mexico","Nevada","New York","Ohio","Oklahoma","Oregon","Pennsylvania","Puerto Rico","Palau","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Virginia","Virgin Islands","Vermont","Washington","Wisconsin","West Virginia","Wyoming","Armed Forces Europe, the Middle East, and Canada","Armed Forces Pacific","Armed Forces Americas"]}

Now in my web app I deserialize JSON and bind to HTML5 dropdown to get following

enter image description here

What I am trying to get to is that; How can I modify JSON data so that when I bind to dropdown, Value is state code and text is full state name so some thing like this

  <option value="IL">Illinois</option>

Upvotes: 0

Views: 2139

Answers (2)

socialMatrix
socialMatrix

Reputation: 1443

Only minor change I had to make from Blaise's reply was as below

  <select data-bind="
     options: states, 
     optionsValue: 'value'// IL, ... 
     optionsText: 'name', // Illinois, ...
     value: lead().state, 
     optionsCaption: 'Choose state...'">
  </select>

Upvotes: 0

Blaise
Blaise

Reputation: 22212

Please note there is options and optionsText in the data-bind attribute for a <select> element.

If you json is:

States:[
    { name:'Illinois', value:'IL'},
    { name:..., value:...},
    ....
]


<select data-bind="
    options: value, // IL, ... 
    optionsText: name, // Illinois, ...
    value: lead().state, 
    optionsCaption: 'Choose state...'">
</select>

Upvotes: 1

Related Questions