在多个选择框中获取最近的选择
Getting recent selection in multiple select box
我想根据多个选择框的选择来填充内容。我可以得到选择框的所有选定值。使用
$('select').change(function(){
console.info($(this).val()) // it gives me array
});
但是我只想要用户最近的选择/取消选择。
你可以这样做:
function arr_diff(a1, a2) {
var a = [],
diff = [];
for (var i = 0; i < a1.length; i++)
a[a1[i]] = true;
for (var i = 0; i < a2.length; i++)
if (a[a2[i]]) delete a[a2[i]];
else a[a2[i]] = true;
for (var k in a)
diff.push(k);
return diff;
}
var oldSelect = [];
$('select').change(function() {
var changes = arr_diff(oldSelect, $(this).val());
console.info(changes); // it gives me array
oldSelect = $(this).val();
});
changes只包含被选中/取消选中的元素
here提琴http://jsfiddle.net/j5rBS/
注:你应该接受一些答案,因为你的录取率非常低
试试这个
// this will set the last selected or deselected option element's value to the select element as a custom attribute "recent"
$("#selectEl option").click(function(event) {
$(this).parent().attr("recent", $(this).val());
});
$("#selectEl").attr("recent"); // returns the last selected/deselected option value or undefined if attribute recent is not present
或者简单地只是在select时获取数组的第一个索引。
$(function(){
$('select').change(function(){
var opt=$(this).val();
$("span").text(opt[0]);
});
})
http://jsfiddle.net/jMw92/10/相关文章:
- 在动态创建的元素上获取对特定选择器的引用
- 获取选择框的状态
- 如何从选择框中的选项中获取属性值
- 从选择下拉菜单中获取数据
- 获取用户选择的不带时区的日期
- 从服务器获取数据并在选择控件中使用ng选项无法显示选项
- jQuery inArray函数在更改选择时未获取值
- Bootstrap点击选择获取点击值
- 根据用户选择获取 JSON 密钥
- 根据另一个字段选择获取新值后更新下拉列表内容
- 根据用户在边栏中的选择获取记录
- 用户选择 - 获取参考以供将来使用
- 选择2:获取格式选择以具有特定的上下文
- j查询选择“获取选择时更改事件”选项
- Angular2的ngFor用于多个选择框.下一步选择获取值
- 根据第一个下拉选择获取值
- 选项选择获取值而不重新加载页面
- 在rails中基于用户选择获取数据库记录
- Javascript:基于下拉选择获取数组
- AngularJS Jasmine单元测试在索引x处选择获取选项