How to prevent multiple selection in jQuery UI Selectable plugin

前端 未结 10 1836
走了就别回头了
走了就别回头了 2020-12-30 00:13

I am using jQuery UI Selectable plugin. I want to select one item at a time. But jQuery UI Selectable plugin allows multiple selection by clicking/ dragging / holding CTRL

相关标签:
10条回答
  • 2020-12-30 00:34

    yes, you can prevent this behavior, just set the toletance option to 'fit'

    0 讨论(0)
  • 2020-12-30 00:35

    This might be a better solution:

    $('#selectable').selectable({
        selecting: function (event, ui) {
            $(event.target).children('.ui-selecting').not(':first').removeClass('ui-selecting');
        }
    });
    
    0 讨论(0)
  • 2020-12-30 00:41

    There are some good solutions here, but most of them assume that you always want to select the first element as it appears in the DOM in a multiple selection case.

    To remedy this, I keep a variable (lastSelection) that contains the last element that was requested successfully (rather than the first in the DOM) to fallback to in the case of an unwanted selection.

    var lastSelection;// this will record our last successful selection
    
    $('#selectable').selectable({
        filter: '.element',
        selecting: function () {
            if ($('.ui-selecting').length > 1) {
                // if selecting multiple (lasso) we will ignore the selection and fallback
                $('.ui-selecting').removeClass('ui-selecting');
                $(lastSelection).addClass('ui-selecting');// if no value, nothing will be selected
            }     
        },
        stop: function () {
            if ($('.ui-selected').length > 1) {
                // looks like we have an invalid selection, fallback to lastSelection
                // this handles the ctrl (windows), cmd (OSX) multi-select cases
                $('.ui-selected').removeClass('ui-selected');
                $(lastSelection).addClass('ui-selected');// if no value, nothing will be selected
            } else {
                if ($('.ui-selected').first().is('.element')) {
                    // if we successfully found a selection, set it as our new lastSelection value
                    lastSelection = $('.ui-selected')[0];
                }     
            }     
        }
    });
    

    Note: If you want to deselect without ctrl / cmd + click you will have to implement a work-around with this method.

    I also wanted to point out that tolerance: 'fit' simply requires that the lasso completely surrounds a target element in order to select it, it will not disable the lasso selection unless your elements cannot be surrounded in the available lasso area. http://api.jqueryui.com/selectable/#option-tolerance

    0 讨论(0)
  • 2020-12-30 00:49

    An interesting discussion about this you can find on this jQuery forum thread.

    0 讨论(0)
提交回复
热议问题