Shreya Rawal Shreya Rawal - 1 month ago 8
JSON Question

How to map json array elements to option selected in drop down list?

I have a json array like this

{Id:[1,2,4,5,8,9,14,22,10,11,12,13,20,21,28,30,31,15,23,32,33,34,35,36,37,38,41,16,24,42,43,48,49,17,25,58,59,61,62,63,64,66,67,68,18,26,69,70,74,75,19,27,82,83,85,86,87,88,89,90,91,108,109,110,111,120]}


and want to select corresponding id when an option is selected from select tag which is also dynamic i.e also a json array which is displayed in select tag option as

<select id="list">
<option>--Select--</option>`enter code here`
<option>List gets updated by the json array</option>
</select>


and I have to do it using jQuery/javascript..any help will be appreciated.

Answer

Use Array#map method to iterate and generate option element using jQuery. Attach change() event handler to listen the event.

var data = {
  Id: [1, 2, 4, 5, 8, 9, 14, 22, 10, 11, 12, 13, 20, 21, 28, 30, 31, 15, 23, 32, 33, 34, 35, 36, 37, 38, 41, 16, 24, 42, 43, 48, 49, 17, 25, 58, 59, 61, 62, 63, 64, 66, 67, 68, 18, 26, 69, 70, 74, 75, 19, 27, 82, 83, 85, 86, 87, 88, 89, 90, 91, 108, 109, 110, 111, 120]
};

$('#list').append(
  data.Id.map(function(v) {
    return $('<option/>', {
      value: v,
      text: v
    })
  })
).change(function() {
  console.log(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="list">
  <option>--Select--</option>
</select>


UPDATE : Since you need to get id based on the option selected update your code as follows. Where you can use Array#indexOf method to get the index of the selected element.

var data = {
  "StoreName": ["10001 Main ST", "10002 Part1", "10004 MyStore1", "10005 M STR", "10008 Centro", "10009 MyStore 02", "1001 G", "1001 H", "10010 Store main ROAD", "10011 Central M Store", "10012 En Department", "10013 M Station", "10014 Test Center", "10015 SubStore1", "10016 AA", "10018 M part #", "10019 Test A - 26032016", "1002 B", "1002 I", "10020 Test Central B "],
  Id: [1, 2, 4, 5, 8, 9, 14, 22, 10, 11, 12, 13, 20, 21, 28, 30, 31, 15, 23, 32, 3, 34, 35, 36, 37, 38, 41, 16, 24, 42, 43, 48, 49, 1, 25, 58, 59, 61, 62, 63, 4, 66, 67, 68, 18, 26, 69, 70, 74, 75, 19, 27, 82, 8, 85, 86, 87, 88, 89, 90, 1, 108, 109, 110, 111, 10]
};
$('#storenm').append(data.StoreName.map(function(v) {
  // generate option with value and text content
  return $('<option>', {
    text: v,
    value: v
  })
})).change(function() {
  console.log(data.Id[data.StoreName.indexOf(this.value)])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <select id="storenm" name="name">
    <option>--Select--</option>
  </select>
</body>

Comments