Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Selectable - cancel current selected element

I have a list containing different some elements. I want all to be selectable, but only in groups. Like:

<ul>
<li rel="group1">Item 1</li>
<li rel="group1">Item 2</li>
<li rel="group2">Item 3</li>
<li rel="group2">Item 4</li>
<li rel="group3">Item 5</li>
<li rel="group3">Item 6</li>
</ul>

I wrote something that could work, but I don't know how to cancel current selection if current's element rel attribute is different to first chosen.

    var selected = null;

    $( "#selectable" ).selectable({
        selecting: function(event, ui) {
            if (!selected)
                selected = $(ui.selecting).attr('rel');

            if (selected != $(ui.selecting).attr('rel')){
               // cancel this selection
            }
        }
    });
like image 442
user1410263 Avatar asked Oct 03 '12 08:10

user1410263


1 Answers

You can use the filter option to enable only certain list items to be selected.

I have prepared this DEMO for you, there was only one trouble with the filter. It doesn't work when changing enabled items from within selecting handler. So I added a little fix into stop handler, where I remove selection from items, that are not enabled.

Your script could look like this:

var locked = false;

function enableAll() {
    $('li').addClass('enabled');
    locked = false;
}

$("#selectable").selectable({

    // allow only enabled items to be selected
    filter: '.enabled',

    selecting: function(event, ui) {

        if (!locked) {

            var group = $(ui.selecting).attr('rel');

            // disable all items belonging to other groups
            $("#selectable li[rel!='" + group + "']").removeClass('enabled');

            locked = true;
        } 

    },

    stop: function() {

        // this fixes selectable behavior 
        // (it ignores dynamically added filter while selecting)
        $(this).find('li.ui-selected:not(.enabled)').removeClass('ui-selected');

        // if no item is selected, then enable all groups
        if($(this).find('.ui-selected').length == 0) {
            enableAll();
        };
    }

});

// initialize
enableAll();​
like image 195
Michal Klouda Avatar answered Nov 07 '22 10:11

Michal Klouda