2

I'm using jQuery Selectable (http://api.jqueryui.com/selectable/) and need to know the number of elements selected once the operation is complete.

//Example Code
$('body').selectable({
    selected: function(event,ui) {
       var $selectedItems = ui.selected;
       alert($selectedItems.length); // This is always 1
    }
});

The variable "selectedItems" returns the elements that are selected. I can loop through them like this:

$selectedItems.each( function() {
    // do something
});

But I simply want to know how many elements are selected.

The "length" property always returns 1. And it doesn't seem right to put a counter in the above loop. There must be some way of doing this?

Thanks for any help.

Andrew
  • 2,691
  • 6
  • 31
  • 47

1 Answers1

3

If you want to run one callback after the selections are made and check how many selections there are, you can use the stop event instead. This is run once after the selection is done. Then, you can check the number of selected items by the class that's added, namely ui-selected.

$( "#selectable" ).selectable({
    stop: function(event,ui) {
       var selectedItems = $('.ui-selected', this);
       console.log(selectedItems.length);
    }
});
  #selectable .ui-selecting {
    background: #ccc;
  }
  #selectable .ui-selected {
    background: #999;
  }
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css">

<ul id="selectable">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129