$(function () {
    $("#draggable-area .draggable-item").draggable({
        // The 'revert' option controls whether the item should return
        // to its original position if not dropped in a valid target.
        // Setting it to 'invalid' will move the item to the droppable area.
        revert: 'invalid'
    });

    $("#droppable-area").droppable({
        accept: ".draggable-item",
        drop: function (event, ui) {
            var itemText = ui.helper.text();
            $(this).append("<div class='dropped-item list-group-item'>" + itemText + "</div");

            // Remove the dragged item from the first div
            ui.helper.remove();
        }
    });

    $("form").submit(function (event) {
        event.preventDefault();

        // Collect the order of dropped items
        var order = [];
        $("#droppable-area .dropped-item").each(function () {
            order.push($(this).text());
        });

        // Store the order in the hidden input field
        $("#order").val(order.join(", "));

        // Submit the form
        this.submit();
    });
});
