user756659 user756659 - 1 year ago 118
jQuery Question

jquery selectable - need to store an array of selected values

I need to create a user selectable grid for each hour of the day. I did some research and came upon jquery selectable as well as this fiddle - http://jsfiddle.net/QGzj9/33/ - which after some modifying will look exactly how I want.

My problem is I need to be able to store an array of the selected values to be able to pass them to php to perform db stuff. So, for instance if an li has the class selected I need to store its value into an array or remove it if unselected.

Also, I do not need the actual selection ability with the mouse. Rather, I would prefer only click to select and click to deselect. I have yet to play around with this much, but the jquery ui is new to me as far as using it.

I included the js below, but the full code/css is shown in the fiddle.

var _selectRange = false, _deselectQueue = [];

$( "#selectable" ).selectable({
selecting: function (event, ui) {
if (event.detail == 0) {
_selectRange = true;
return true;
}
if ($(ui.selecting).hasClass('ui-selected')) {
_deselectQueue.push(ui.selecting);
}
},
unselecting: function (event, ui) {
$(ui.unselecting).addClass('ui-selected');
},
stop: function () {
if (!_selectRange) {
$.each(_deselectQueue, function (ix, de) {
$(de)
.removeClass('ui-selecting')
.removeClass('ui-selected');
});
}
_selectRange = false;
_deselectQueue = [];
}
});


EDIT SOLUTION :

I thought this through some more last night and this morning and decided to completely eliminate the use of ui selectable. I just did not see the point when I only needed a simple toggle functionality (the mouse dragging selection is not important to me). Here is the resulting js which seems to work perfectly fine for me.

$('#selectable li').on('click', function() {
$(this).toggleClass('ui-selected');
});

function getSelected() {
var selectedVals = [];
$('.ui-selected').each(function(k,v) {
selectedVals.push($(v).text());
});
alert(selectedVals);
}

$('#getVals').click(function() {
getSelected();
});

Answer Source

FIDDLE

  function getSelected() {
    var selectedVals = [];
    $('.ui-selected').each(function(k,v) {
        selectedVals.push($(v).text());
    });
    alert(selectedVals);
  }

var selectedVals = getSelected();

When this function is called it will get all selected values in selectedVals array which you can pass to PHP.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download