简体   繁体   中英

How to get values from json array fill a Selection (drop down)

I am new to jquery and I am currently building an application in phonegap...

I need to get a list of values displayed into the dropdown..

 "data": [
    {
      "city_id": "1",
      "city": "test1"
    },
    {
      "city_id": "2",
      "city": "test2"
    },
]

I get my data like this... I want to fill these values in the drop down which is found in a form. When the user selects the city in the form I want the form to post city_id when it is posting the form data....

Any kind of help is appreciated....

Its fairly straightforward with jQuery

Html

<select></select>

JS

var d = '"data": [{"city_id": "1","city": "test1"},{"city_id": "2","city": "test2"}]';
var d = JSON.parse('{'+d+'}');

$.each(d.data, function(index, value){
  $('select').append('<option value="'+value.city_id+'">'+value.city+'</option>')
});

And there you have it!

Here is a JSfiddle

You can dynamically load each of these options into a <select> html element via jquery.

Each of these options would display the city as text, and city_id as value. JS has a way of parsing JSON into a JS object by the function JSON.parse() .

Here's a codeblock you can reference:

var data = JSON.parse(*your data above*); // This is now an array
var $menu = $('#menu'); // this is in reference to the <select> menu you have in your HTML that you are appending to
for (var i = 0; i < data.length; i++) {
    var city = data[i];
    $menu.append('<option value='+city.city_id+'>'+city.city+'</option>');
}

This will populate your menu based on the JSON, and you can wrap the whole thing in a element so that it will pass the currently selected option on form submit.

You can show your city as text, city_id you can store as attr "city_id" in your tag:

<div city_id="(city_id)">(city)</div>

and show it on click with jquery.

$("div[city_id]").click(function(){
alert($(this).attr("city_id"));
})

Hear some example : https://jsfiddle.net/RomanGroovyDev/hh2ydecb/

You can try this:

HTML

<select></select>

Data

var dataObj =  {"data": [
    {
      "city_id": "1",
      "city": "test1"
    },
    {
      "city_id": "2",
      "city": "test2"
    },
]}

Script

Using forEach:

dataObj.data.forEach(function (obj) {        
   $("<option />", {value: obj.city_id, text: obj.city}).appendTo($('select'));
})

Using for in:

for(i in dataObj.data) {
    $("<option />", {value: dataObj.data[i].city_id, text: dataObj.data[i].city}).appendTo($('select'));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM