jQuery selectable manually invoke an event

102 Views Asked by At

I have some jQuery selectable objects. Some items of that objects are selected by default, so i have something like this:

HTML

<ol id='lunedi'>
    <li class='ui-state-default ui-selected' id='lunedi-1'>1</li>
    <li class='ui-state-default' id='lunedi-2'>2</li>
    <li class='ui-state-default' id='lunedi-3'>3</li>
    <li class='ui-state-default ui-selected' id='lunedi-4'>4</li>
<ol id='martedi'>
    <li class='ui-state-default ui-selected' id='martedi-1'>1</li>
    <li class='ui-state-default ui-selected' id='martedi-2'>2</li>
    <li class='ui-state-default' id='martedi-3'>3</li>
    <li class='ui-state-default' id='martedi-4'>4</li>

JS

// multiple selection
$(function() {
    //$("#lunedi").selectable();
    $("#lunedi").bind("mousedown", function(e) {
        e.metaKey = true;
    }).selectable();
});

// code for serialization
$(function() {
    $("#lunedi").selectable({
        stop: function() {
            var result = $("#result-lunedi").empty();
            $(".ui-selected", this).each(function() {
                //var index = $( "#lunedi li" ).index( this );
                var index = $(this).attr('id');
                result.append("#" + index);
            });
        }
    });
});

I would like to serialize the checked items, but it works fine only if i modify the selection status at least to one of the items of the <ol>.

I think it happens because Javascript is invoked only during the event "stop", so if I don't select/unselect nothing, serialization code won't execute.

The solution should be to manually invoke the stop routine, or to perform a double toggle to an items before processing data (in order to serialize the results without changing the value), but I'm really confused about how to do this.

1

There are 1 best solutions below

1
On

use same serialization function on create

// code for serialization
$(function() {
    var updateResult = function () {
        var result = $("#result-lunedi").empty();
        $(".ui-selected", this).each(function() {
            //var index = $( "#lunedi li" ).index( this );
            var index = $(this).attr('id');
            result.append("#" + index);
        });
    };
    $("#lunedi").selectable({
        create: updateResult,
        stop: updateResult
    });
});