1

I have an array like this:

[
  [{
    "station_territory": "Peshawar-CMD"
  }, {
    "station_territory": "Faisalabad-CMD"
  }],
  [{
    "station_territory": "Faisalabad-FEM"
  }]
];

How can I assign it to a multiple drop down where the id is the station? I tried this code:

$.each(data, function(index, value) {
  $("#station") = value;
});
0

1 Answer 1

1

To create option elements within the select you can loop through each level of the arrays in data create the option elements which you can assign to the select.

Note that in jQuery you never assign anything to a jQuery object itself; you use the methods that jQuery provides in order to amend elements. In this case you can use append():

var data = [
  [{
    "station_territory": "Peshawar-CMD"
  }, {
    "station_territory": "Faisalabad-CMD"
  }],
  [{
    "station_territory": "Faisalabad-FEM"
  }]
];

var options = [];
data.forEach(function(outer) {
  outer.forEach(function(inner) {
    options.push(`<option value="${inner.station_territory}">${inner.station_territory}</option>`);
  });
});
$("#station").append(options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple id="station"></select>

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

6 Comments

an error generate , can u plz resolve it `index.php?action=edit_employee&empID=5309:4393 Uncaught TypeError: data[0].map is not a function
Possibly try data = JSON.parse(data) first.
now its working but if the response is ` [[{"station_territory":"City0"},{"station_territory":"City1"}],[{"station_territory":"City2"}]] ` its showing only 1st two values not 3rd
That's because it's a completely different data structure. You now have multiple arrays at different levels.
i just want to dynamically append values from json array to multiple based drop down
|

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.