How to get values of a multiselect Listbox in order they were clicked?

只谈情不闲聊 提交于 2021-02-07 10:49: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

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 ?

EDIT

Getting the most recent value selected also solves my problem.

How to get most recent selected item ?


回答1:


First, set an event that adds an integer to each listbox item whenever the user clicks. Store the integer in a hidden element somewhere on the page, or do something clever by setting a data-attribute on the element like this:

$(function() {
    $("#ListBox").data("selected-index", 0);
});

$("#ListBox option").on("click", function() {
    var currentSelectedIndex = $("#ListBox").data("selected-index");
    $(this).data("counter", currentSelectedIndex++);
});

Then in order to get all those in the order they've been clicked:

function getOrderOfItems() {
    var arrayOfSelected = new Array(),

    // Use Math and .map() to get the highest data-counter:

    counters = $("#ListBox option[data-counter]").map(function() {
        return parseInt($(this).data("counter"), 10);
    }).get();

    var highestCounter = Math.max.apply(Math, counters);

    // We have the highest counter, so use a for loop to select the selected options.
    for (var i = 0; i < highestCounter; i++) {
        arrayOfSelected.push($("#ListBox option[data-counter=" + i + "]"));
    }

    console.log(arrayOfSelected);
    return arrayOfSelected;
}

Where arrayOfSelected contains the ListBox items in the order they were clicked.




回答2:


Note, html from @PaulRoub 's Answer used , as no html appear at OP

If interpret Question correctly , try substituting change event for click event ; creating an array of selected values , utilize .slice(-2)[0] to view previously selected item .

$("#ListBox").data("prev", []).change(function(e) {
  $(this).data().prev.push(this.value)
  console.log($(this).data().prev.slice(-2)[0], // last selected item
      $(this).data().prev) // array of selected items , in order selected
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<select id="ListBox" multiple>
  <option value="3000">3000</option>
  <option value="3001">3001</option>
  <option value="3002">3002</option>
  <option value="3003">3003</option>
  <option value="3004">3004</option>
</select>



回答3:


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() 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 .


来源:https://stackoverflow.com/questions/32251585/how-to-get-values-of-a-multiselect-listbox-in-order-they-were-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!