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.

2
  • Can create stacksnippets , jsfiddle jsfiddle.net to demonstrate ? Commented Aug 31, 2015 at 18:33
  • Have you tried wrapping your code in a $(document).ready(function() { //your code }? Commented Aug 31, 2015 at 18:38

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.