我想使用对象填充下拉列表选项。例如,我有对象
{"877":["email1@email.com"],"905":["email2@email.com"],"967":["email3@email.com"],"2":["email3@email.com","email5@email.com"]}
此下拉列表将取决于另一个下拉列表,在通过下拉列表选择公司后,此电子邮件下拉列表将根据所选公司代码填充。877,905,967,2 是公司代码。
我想使用对象填充下拉列表选项。例如,我有对象
{"877":["email1@email.com"],"905":["email2@email.com"],"967":["email3@email.com"],"2":["email3@email.com","email5@email.com"]}
此下拉列表将取决于另一个下拉列表,在通过下拉列表选择公司后,此电子邮件下拉列表将根据所选公司代码填充。877,905,967,2 是公司代码。
我认为您希望第二个下拉菜单的内容根据第一个下拉菜单的内容而改变。如果是这种情况,我会这样做:
html:
Company code: <select id="cc"></select>
<br/><br/>
Email: <select id="email"></select>
代码:
$(document).ready(function() {
var data = {
"877":["email1@email.com"],
"905":["email2@email.com"],
"967":["email3@email.com"],
"2":["email3@email.com","email4@email.com"]};
$("#cc").change(function() {
$("#email").empty();
$.map(data[$(this).children(":selected").val()],
function(val) {
$("#email").append($("<option></option>").val(val).html(val));
});
});
for (var id in data) {
$("#cc").append($("<option></option>")
.val(id).html(id));
}
$("#cc").trigger("change");
});
也许不是更快的解决方案,但工作:
代码:
var obj = {
"877": ["email1@email.com"],
"905": ["email2@email.com"],
"967": ["email3@email.com"],
"2": ["email3@email.com", "email5@email.com"]
};
var select = $('<select></select>');
$.each(obj, function (index, val) {
if (obj[index].length > 1) {
$.each(obj[index], function(index2, val2){
var option = $('<option value="' + index + '">' + val2 + '</option>');
select.append(option[0]);
});
} else {
var option = $('<option value="' + index + '">' + val + '</option>');
select.append(option[0]);
}
})
$('body').html(select);
$(document).ready(function() {
var data = {
"-- Select Date --":["-- Select Date First Then Slot --"],
"06-Dec-2013":["10:00-12:00","2:00-4:00"],
"07-Dec-2013":["14:00-16:00"]};
$("#exmDtId").change(function() {
$("#exmSlotId").empty();
$.map(data[$(this).children(":selected").val()],
function(val) {
$("#exmSlotId").append($("<option></option>").val(val).html(val));
});
});
for (var id in data) {
$("#exmDtId").append($("<option></option>")
.val(id).html(id));
}
$("#exmSlotId").append($("<option></option>")
.val("-- Select Date First Then Slot --").html("-- Select Date First Then Slot --"));
//$("#exmDtId").trigger("change");
});
<table width="100%" border="0" cellpadding="5">
<tr>
<td width="30" align="center">
<SPAN class="caption"><font color="red">*</font> </SPAN>
</td>
<td width="220">
Exam Date
</td>
<td width="350">
<select id="exmDtId"></select>
</td>
</tr>
<tr>
<td width="30" align="center">
<SPAN class="caption"><font color="red">*</font> </SPAN>
</td>
<td>
Exam Batch
</td>
<td>
<select id='exmSlotId' name='exmSlot'></select>
</td>
</tr>
</table>