Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery sortable - sort based on value of input field

Disclaimer - I'm not entirely sure this is even possible. But in that case, I'd still like someone to point out a possible alternative or a hack of some sort.

Here's the situation.

I have a working list which uses jQuery UI Sortable so the user can drag and drop the items on the list.

The jQuery:

$(document).ready(function() {
    $("#test-list").sortable({
      handle : '.big-handle',
      update : function () {
          var order = $('#test-list').sortable('serialize');
        $("#info").load("../sortable/process-sortable.php?"+order);
      }
    });
});

The Ajax part stores the new order in the database, you don't need to worry about that.

The HTML:

<ul id="test-list">
<li id='listItem_1'><div class='main-item big-handle'><img src='../sortable/arrow.png' alt='move' width='16' height='16' class='handle' /><strong>Item 1</strong></div></li>
<li id='listItem_2'><div class='main-item big-handle'><img src='../sortable/arrow.png' alt='move' width='16' height='16' class='handle' /><strong>Item 1</strong></div></li>
<li id='listItem_3'><div class='main-item big-handle'><img src='../sortable/arrow.png' alt='move' width='16' height='16' class='handle' /><strong>Item 1</strong></div></li>
</ul>

That all works fine. Now, the tricky part. My client wants an input field next to each list item where the user can enter a number, which should onBlur move that list item to the specified position. So if the user enters "1" into the field next to list item no. 3, then that item should move to the first spot on the list, just as if it was dragged there. Can this be done?

No need for you to come up with a full solution for the whole list, let's say that I just need a field which would move item no. 3 around.

like image 338
sveti petar Avatar asked Nov 13 '22 04:11

sveti petar


1 Answers

How about this: jsFiddle example.

$("#test-list").sortable({
    handle: '.big-handle',
    update: function() {
        var order = $('#test-list').sortable('serialize');
        $("#info").load("../sortable/process-sortable.php?" + order);
    }
});

$("#test-list input").blur(function() {
    var pos = $(this).val() - 1;
    if (pos >= 0 && pos <= $("#test-list li").length - 1) {
        if ($(this).parents('li').index() > pos) {
            //move up
            $(this).parents('li').insertBefore($("#test-list li:eq(" + pos + ")"));
        }
        if ($(this).parents('li').index() < pos) {
            //move down
            $(this).parents('li').insertAfter($("#test-list li:eq(" + pos + ")"));
        }
        $("#test-list input").val('');
    }
});​
like image 156
j08691 Avatar answered Nov 16 '22 02:11

j08691