在jquery中使用两个下拉菜单



我有一个下拉列表,其选定值由以下代码获取:

$(document).on('change','#DropDown1',function()
{
var value1 = $(this).children("option:selected").val();
var data = {"key": value1};
$.ajax({
url : "value_choices",
type: "GET",
data: data,
dataType: "json"
});

现在我有两个下拉列表,而不是第二个下拉列表的id为DropDown2的下拉列表。如何获取两个下拉列表的值?我搜索到目前为止,我认为我应该使用这样的方法:

$(document).on('change','#DropDown1, #DropDown2',function()
{
var value1 ,value2= $(this).children("option:selected,option:selected").val(); 
//I know that the above written line of code is absolutely wrong. I need your help in this.
//Moreover please check whether rest of the code is right or not.
var data = {"key": value1,"color":value2};
$.ajax({
url : "value_choices",
type: "GET",
data: data,
dataType: "json"
});

更新这是我在应用程序中使用的实际代码。

<script type="text/javascript">
$(document).on('change','#keyDropDown, #valueOfKey',function()
{
//var chosenKey = $(this).children("option:selected").val();
var chosenKey = $('#keyDropDown').val();
var chosenValue = $('#valueOfKey').val();
var data = {"key": chosenKey,"value":chosenValue};
$.ajax({
url : "value_choices",
type: "GET",
data: data,
dataType: "json",
success: function(response){
if(response.data) {
var valueDropDown = $('#valueOfKey');
valueDropDown.empty();
for( var item of response.data)
{
valueDropDown.append('<option value=' + item + '>' + item + '</option>');
}
}
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.n' + jqXHR.responseText;
}
$('#post').html(msg);
},
});
});
</script>

您可以将更改事件添加到两个下拉列表中,并通过它们的id 获取每个下拉列表的值

$(document).on('change','#DropDown1, #DropDown2',function()
{
var value1 = $('#DropDown1').val();
var value2 = $('#DropDown2').val();
var data = {"key": value1,"color":value2};
$.ajax({
url : "value_choices",
type: "GET",
data: data,
dataType: "json"
});

最新更新