我是javascript(Json)的初学者。我正在尝试根据另一个下拉列表的选择填充下拉框。正如你在下面的图像中看到的那样,我试图填充"规则选择"基于"产品模板"的下拉菜单落下。尝试的代码也可用。
任何帮助都将不胜感激。
谢谢
function drFilter()
{
var productTemp = $('#ddlProdTemp :selected').val();
$.getJSON('ptdrFilter', { productTemplate: productTemp }, function (result) {
var ddl = $('#ddl2');
var length = result.length;
ddl.empty();
if (length > 0) {
$(document.createElement('option'))
.attr('value', 0)
.text("-- Please Select --")
.appendTo(ddl);
}
$(result).each(function (will) {
//
$(document.createElement('option'))
.attr('value', result[will])
.text(result[will])
.appendTo(ddl);
});
});
}
public ActionResult ptdrFilter(int id)
{
IUnitOfWork uow = DataAccess.GetUnitOfWork();
using (ManageProductTemplate ptLogic = new ManageProductTemplate(ref uow))
{
List<ProductTemplate> currentpt = ptLogic.GetBy(x => x.ProductTemplateID == id);
List<string> pt = new List<string>();
foreach (var item in currentpt)
{
pt.Add(item.DistributionRule.Name);
}
return Json(pt);
}
}
答案 0 :(得分:0)
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-3.1.0.slim.min.js"></script>
</head>
<body>
<select id="main">
<option value="a">A</option>
<option value="b">B</option>
</select>
<select id="subselect"></select>
<script>
var sampleData = { a: { value1: "text 1 in a", value2: "text 2 in a" }, b: { value1: "text 1 in b", value2: "text 2 in b" } };
var dataInJSONForm = JSON.stringify(sampleData);
var datainJSObjectForm = JSON.parse(dataInJSONForm);
$('#main').on('change', function (e) {
var valueChosenInMain = $(this).val();
var options = datainJSObjectForm[valueChosenInMain];
var $subselect = $('#subselect');
$subselect.children().detach();
for (var property in options) {
$subselect.append($('<option>', { value: property, text: options[property] }));
}
});
</script>
</body>
</html>