Jquery UI SELECTABLE, how to select one item only?
Asked Answered
E

3

14

is there any way to define that, only one item can be selected with jquery.selectable widget?

Or i've to inmplement a workarround capturing events and manipulating by my self what happens?

Eakins answered 2/5, 2011 at 10:10 Comment(2)
Do you want to deselect a previously-selected item? Or prevent the selection of a second item?Devilment
what i pretend is to get only one item selected like a "dropdown behavior" or a radiobutton.Eakins
A
10
$("#myList li").click(function() {
  $(this).addClass("selected").siblings().removeClass("selected");
});
Araiza answered 2/5, 2011 at 11:8 Comment(2)
selected should be ui-selectedPeters
Also, this doesn't handle the mouse select case.Peters
P
25

I expanded on Nirmal's answer to limit the mouse select case. Also, I feel that it is cleaner to use the selected option rather than a completely separate event handler.

$("#selectable").selectable({
    selected: function(event, ui) { 
        $(ui.selected).addClass("ui-selected").siblings().removeClass("ui-selected");           
    }                   
});

There is one minor problem remaining. When selecting multiple items with the mouse the last item will always be selected. This is because the function passed into the selected option is run for each selected item, which I assume goes in item order. Ideally the item that your mouse cursor lands at would be selected. I didn't fix this because I mainly just wanted a multiple selection constraint when using the mouse.

Peters answered 5/12, 2012 at 16:12 Comment(2)
+1 This works great. (In my particular case the items do not have descendants.)Stannic
To disable multiple items getting caught in the lasso: $("#selectable").selectable({ selected: function(event, ui) { $(ui.selected).addClass("ui-selected").siblings().removeClass("ui-selected"); }, selecting: function(event, ui) { $(ui.selecting).addClass("ui-selecting").siblings().removeClass("ui-selecting"); }, });Finedraw
A
10
$("#myList li").click(function() {
  $(this).addClass("selected").siblings().removeClass("selected");
});
Araiza answered 2/5, 2011 at 11:8 Comment(2)
selected should be ui-selectedPeters
Also, this doesn't handle the mouse select case.Peters
S
8

I improve mattblang's answer a little. Siblings can have also descendants, so more general answer is:

$("#selectable").selectable({
    selected: function(event, ui) {
        $(ui.selected).addClass("ui-selected").siblings().removeClass("ui-selected").each(
            function(key,value){
                $(value).find('*').removeClass("ui-selected");
            }
        );
    }
});
Stirring answered 10/10, 2013 at 22:7 Comment(1)
thats better... improved answeredHirundine

© 2022 - 2024 — McMap. All rights reserved.