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
}
}
});
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With