这是一个非常简单的问题,但我似乎无法弄明白。
我有数据类型场景的表单,有人可以输入有关所提供服务的信息。所以表单看起来像这样
我想根据选择服务类型列表填充相应的服务列表,所以我有以下代码:
$(document).ready(function() {
$("select#serviceType").change(function() {
var serviceId = $("#serviceType > option:selected").attr("value");
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "GetServicesByServiceType/" + serviceId,
data: "{}",
dataType: "json",
success: function(data) {
var options = '';
for (index in data) {
var service = data[index];
options += "<option value='" + service.ServiceId + "'>" + service.Name + "</option>";
}
$("#services").removeAttr('disabled').html(options);
}
}
);
});
});
我遇到以下问题:
非常感谢任何帮助!
答案 0 :(得分:1)
我将假设ServiceType,Service,Info的每个三元组
被封装在自己的<div>
容器中,如下所示:
<div> <select class="type"> <option value="type1">ServiceType 1</option> <option value="type2">ServiceType 2</option> </select> <select class="service"/> <input type="text" /> </div>
正如您所看到的,ServiceType <select>
标有class
属性,以便更容易定位。因此,假设您的所有ServiceType列表都有class=type
,您现在可以编写
$(function(){
$('select.type').change(function(){
var serviceId=$(this).val(); //'this' keyword refers to
//the dropdownlist that triggered the event
$.ajax({
... //other stuff
success: function(data){
... //parse data
/*siblings('select') will select all
the other <select> elements in the same container,
which now happens to be the <select class='service'/>
inside the parent <div>*/
$(this).siblings('select').removeAttr('disabled').html(options);
}
});
});
});
要让您的服务下拉列表在更改时刷新,现在应该是非常简单的:
$('select.service').change(function(){
... //do stuff here
});
要在页面加载上执行任何操作,只需在
中包含您的语句即可$(function(){
...//will execute after dom is ready, ie after page loads
});
块
答案 1 :(得分:1)
好的,我能够搞清楚。当值发生变化时,这将更新TR内的每个级联下拉列表,并在加载时运行:
$(document).ready(function() {
var populateDropDowns = function() {
var currentDropdown = $(this);
var serviceId = $(this).val();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/GetServicesByServiceType/" + serviceId,
data: "{}",
dataType: "json",
success: function(data) {
var options = '';
for (index in data) {
var service = data[index];
options += "<option value='" + service.ServiceId + "'>" + service.Name + "</option>";
}
currentDropdown.closest('tr').find("select.services").html(options);
}
}
);
};
$('select.currentServices').each(populateDropDowns);
$('select.currentServices').change(populateDropDowns);
});