javascript - 在多选中获取当前选项
问题描述
如何在 Jquery 中获取当前选中/未选中multiselect
?
我已经知道如何在multiselect
. 问题是我需要获取用户单击时当前已选择/未选择的那个。这看起来像一个微不足道的问题,但到目前为止我还没有真正找到合适的解决方案。
这是我之前尝试过的:
$('#mySelect').change(function(){
var element = $(this).val();
})
不幸的是,它返回一个包含所有选定选项的数组。我需要的是获取用户当前选择或未选择的值。我只是尝试使用辅助变量自己创建一个方法,现在看来它可以工作了。
if($(this).attr('id').includes('Type')) Key = "trackertype";
if(selectedValue.length > 0 && $(this).val() == null){
Value = selectedValue[0].toString();
selectedValue = [];
Key = '-' + Key;
}else if(selectedValue.length == 0 && $(this).val() != null){
selectedValue.push($(this).val()[0]);
Value = selectedValue[0].toString();
}else if(selectedValue.length > 0 && $(this).val() != null && selectedValue.length < $(this).val().length){
var selected = true;
$.each($(this).val(),function(i,item){
var current = item.toString();
$.each(selectedValue,function(i,itemV){
if(current != itemV.toString()){
Value = current.toString();
selectedValue.push(current.toString());
selected = false;
}
});
});
}else if(selectedValue.length > $(this).val().length){
$.each($(this).val(),function(i,item){
var current = item.toString();
$.each(selectedValue,function(i,itemV){
if(current != itemV.toString()){
Value = itemV.toString();
selectedValue = jQuery.grep(selectedValue, function(value) {
return value != itemV.toString();
});
selected = true;
}
});
});
}
if(selected){
Key = '-' + Key;
}
我需要将值(当前选定选项的值)和键(选择名称)发送到 Web 服务。它不是最好的代码(对此感到抱歉),但它确实完成了它的工作。
谢谢
解决方案
var selectedItems = document.querySelectorAll('#selectBoxid option:checked');
// here selectboxid is id of select element of your page.
当任何 html 元素都可以使用时,这很简单document.getElementsById('id')
。
就像您想使用 css 类或任何 css 选择器而不是元素的 id 或 html 元素的名称来获取 html 元素一样。
例如 :
<p class="text-center" > abcd </p>
然后,我们可以使用以下方法检索所有 html:
document.querySelectorAll('.text-center')
在给定的示例中,我们想要为我使用的属性选择的选项 html 元素:
document.querySelectorAll('option:checked');
推荐阅读
- node.js - 为什么我在尝试读取过去的交易时从贝宝获得代码 404
- node.js - 我想在 MongoDB 中列出用户和所有用户的评论。可能吗?
- spring - Spring Cloud Gateway Predicate中matchOptionalTrailingSeparator有什么用
- html - 如何在倾斜的 div 中使图像“正常”?
- python - 应用返回包含列表的元组的函数时出现 Pandas AssertionError
- docker - 容器优化操作系统 (Docker) 上的 SSL 证书
- uwp - UWP 地图控件 - 调整 MapIcon 图像的大小
- c# - 创建不重复调用代码的类
- node.js - 在 Node.js 中读取计算机的声音输出并分析声音
- python - 如何设置索引 NaN(空单元格)