javascript - 在 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"
});
推荐阅读
- jhipster - 将 JHipster 实体子生成器集成到现有项目中
- python - Django - 获取登录用户组的列表。没有数据或“无法将关键字‘组’解析到字段中。选项有:id、名称、权限、用户”
- node.js - 模块解析失败,webstorm,Ionic 应用
- java - 如何将 URI 作为 jpg 文件保存到内部存储上的自定义文件夹中?
- javascript - 防止在不使用 onclick 功能的情况下使用 jquery 检查单选按钮
- git - 更改子模块时更新 git 子模块
- python - 纯 Python 模式下的 Cython,在 C 代码中使用 python 类
- python-3.x - python中空字典列表的初始化
- html - 在创建 html 输入属性中是否有任何级别的重要性
- c# - 具有 MySql 连接的实体框架不起作用