如何按单击顺序获取多选列表框的值? [英] How to get values of a multiselect Listbox in order they were clicked?

查看:23
本文介绍了如何按单击顺序获取多选列表框的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多选列表框并使用

I have a multiselect Listbox and fetching the list of selected values using

$('[id*=ListBox]').click(function(){

    var selectedItems = $(this).val();
    var lastItem = $("[id*=ListBox] option:selected").last().val();

});

这会返回以逗号分隔的选定值数组.但问题是数组总是按值排序,而不是按所选值被点击的顺序生成.

This returns me comma separated array of selected values. But the problem is the array is always sorted by values and not generated by order in which selected values were clicked.

3000、3005、3009、3011

但是如果我先点击值为 3011 的项目,然后是 3005 ,然后是 3000 和最后 3009 我想要这个顺序的值

But if I first click item with value 3011, then 3005 , then 3000 and last 3009 I want values in that order

3011、3005、3000、3009

如何按点击顺序获取选定的值?

How to get selected values in order in which they were clicked ?

编辑

选择最新的值也解决了我的问题.

Getting the most recent value selected also solves my problem.

如何获取最近选中的项目?

How to get most recent selected item ?

推荐答案

这对我有用.我不得不采用一个全局数组,每次点击后将列表框的选定项目与数组中的元素进行比较.他们之间的差异给了我最新的选择项.

This is what worked for me . I had to take a global array and after each click compare selected items of listbox with elements in array . The difference between them gave me latest selected item .

$(document).ready(function () {
            var arr = [];
            $("[id*=listBox]").click(function () {
                var lastItem = '';
                var selArr = [];
                var flag = 0;

                selArr = $(this).val();
               // alert(selArr);
                if ( $(this).val()!=null) {
                    if ($(this).val().length > 2) {

                        lastItem = $(selArr).not(arr).get();

                        selArr = $.grep(selArr, function (value) {
                            return value != lastItem;
                        });
                        flag = 1;
                        //arr = [];
                    }
                }
                arr = selArr;
                $(this).val(selArr);

                if (flag == 1)
                    alert("Cannot select more than 2 items");

            });
        });

这个问题让我发现了两件奇怪的事情.

This question made me discover two strange things .

  1. $("#Listbox option").click() 不会在 Internet Explorer 上触发(我使用的是版本 9)但是在其他人身上效果很好.我不知道为什么选项元素不在在 IE 中获取.
  2. $(#Listbox).val() 给出以逗号分隔的选定值列表排序顺序而不是选择项目的顺序.这个事实证明这是一个重大的惊喜和头痛.
  1. $("#Listbox option").click() doesn't fire on Internet explorer ( i used version 9 ) but works fine on others . I don't know why option element in not fetched in IE.
  2. $(#Listbox).val() gives comma seprated list of selected values in sorted order and not in order in which the items were selected. This proved to be a major surprise and headache .

这篇关于如何按单击顺序获取多选列表框的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆