How to programmatically select selectables with jQuery UI?

Svish picture Svish · Jun 29, 2010 · Viewed 17.7k times · Source

I have a range of items that are selectable. I would like to add a button somewhere that activates a preset selection amongst those. Is there a way I can do that?

What I would like is to tell it to "Select these guys" and then have all the events and all fired as normal, so I don't have to call all of those selection events manually.

More info: The events that I talk about are the ones listed in their api and on their demo page:

  • selected
  • selecting
  • start
  • stop
  • unselected
  • unselecting

And also, I think there might be data that is set/cleared as well when selecting things. So it's not just to add those css classes.

Answer

Homer picture Homer · Feb 23, 2012

Here is a variation of Alex R's code working with multiple elements

http://jsfiddle.net/XYJEN/1/

function SelectSelectableElements (selectableContainer, elementsToSelect)
{
    // add unselecting class to all elements in the styleboard canvas except the ones to select
    $(".ui-selected", selectableContainer).not(elementsToSelect).removeClass("ui-selected").addClass("ui-unselecting");

    // add ui-selecting class to the elements to select
    $(elementsToSelect).not(".ui-selected").addClass("ui-selecting");

    // trigger the mouse stop event (this will select all .ui-selecting elements, and deselect all .ui-unselecting elements)
    selectableContainer.data("selectable")._mouseStop(null);
}

Update:

jQueryUI 1.10, per comments from kmk: http://jsfiddle.net/XYJEN/163/