我有一个像这样的json数组
{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]}
并且当从select标签中选择一个选项时也想选择相应的id,这也是一个动态的,也就是一个json数组,它在select标签选项中显示为
<select id="list">
<option>--Select--</option>`enter code here`
<option>List gets updated by the json array</option>
</select>
我必须使用jQuery / javascript来实现。任何帮助都将不胜感激。
答案 0 :(得分:1)
使用 Array#map
方法迭代并生成option element using jQuery。附加 change()
事件处理程序以侦听事件。
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);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="list">
<option>--Select--</option>
</select>
&#13;
更新:由于您需要根据所选的选项获取ID,请按以下方式更新您的代码。您可以使用 Array#indexOf
方法获取所选元素的索引。
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)])
})
&#13;
<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>
&#13;