Search code examples
jqueryhtmljquery-uiinputdroppable

jQuery UI Droppable - storing element order in input field


Link of setup: https://jsfiddle.net/7b8bqzsh/1/

Can see full working example using link above. The plan is to store the order of the links into a input field so that it can be saved to a database.

Currently have the IDs pulling into the input field, but only the latest ID is shown. Is there a way to make this an array of stored variables, shown in the order that they are in the droppable elements, separated by a comma?

Code:

$(".social-msl-link-label").draggable({
    connectToSortable: ".social-msl-group-list",
    revert: "invalid",
    helper: "clone"
});

var orderMSLids = [];
$(".social-msl-links-order li").droppable({
    accept: ".social-msl-link-label",
    tolerance: 'pointer',
    greedy: true,
    hoverClass: 'highlight',
    drop: function(ev, ui) {
        orderMSLids = [];
        $(ui.draggable).clone(true).detach().css({
          position: 'relative',
          top: 'auto',
          left: 'auto'
        }).appendTo(this);

        orderMSLids.push($(this).find('.social-msl-link-label').attr('id'));

        $(this).siblings().filter(function() {
          return $(this).text().trim() === $(ui.draggable).text().trim();
        }).empty();
        $('#msl-order').val(orderMSLids);
    }
});

Solution

  • I modified your jsFiddle.

    as you can see, the logic I applied, is to go through all the items in the list which clones the dragged elements, so I pick them up and all in the right order.

    creating an array of the ids, then do a join, sandwiching the coma.

    I hope it helps you.

    Your removed code:

    $('#msl-order').val(orderMSLids);
    

    My code:

    // edited
    str = [];
    $(".social-msl-links-order li").each(function( index ) {
      //console.log( index + ": " + $( this ).children().attr('id') );
      var res = $( this ).children().attr('id');
      if (res) {
        str.push(res);
      }
    });
    
    var string = str.join(",");
    console.log(string);
    $('#msl-order').val(string);
    

    Working JSFinddle


    COMPLETE WORKING EXAMPLE

    here you have complete resolve.

    More code added

    $(this).empty(); // added to remove previous content
    

    Complete Working JSFinddle