0

I'm using JQuery Sortable UI Where I need to track current position array of <li> Here is code

$(document).ready(function() {
    $('#sortable').sortable({
        update: function(event, ui) {

            $('#sortable').children().each(function(i) {
                var id = $(this).attr('data-post-id')
                    ,order = $(this).index() + 1;

                $('#console').val($('#console').val() + '' + id + '' + ',');

            });

        }
    });
});

& here is HTML

<ul id="sortable">
    <li data-post-id="1">Post 1</li>
    <li data-post-id="2">Post 2</li>
    <li data-post-id="3">Post 3</li>
    <li data-post-id="4">Post 4</li>
    <li data-post-id="5">Post 5</li>
    <li data-post-id="6">Post 6</li>
    <li data-post-id="7">Post 7</li>
</ul>

<input id="console" type="text" />

On sorting, I want current position array of <li> to be printed inside input area.

This code works fine except :

On .each() sorting, arrays are appending within input area. What I want is to Replace previous arrays with new arrays

Here is Fiddle that will give you an Idea of what I'm talking about.

I tried wrapping inside .change() function but I'm not getting it correctly.

Any help would be appreciated!

Thanks

2 Answers 2

2

Instead of appending, push the id into an array outside each()

$(document).ready(function() {
    $('#sortable').sortable({
        update: function(event, ui) {
            var foo = [];
            $('#sortable').children().each(function(i) {
                var id = $(this).attr('data-post-id')
                    ,order = $(this).index() + 1;
                foo.push(id);
            });
            $('#console').val(foo);
        }
    }); 
});
Sign up to request clarification or add additional context in comments.

Comments

0
$('#sortable').sortable({
     update: function(event, ui) {
          $('#console').val("");
          $('#sortable').children().each(function(i) {
             var id = $(this).attr('data-post-id'),order = $(this).index() + 1;                  
             $('#console').val($('#console').val() + '' + id + '' + ',');              
           });          
     }     
}); 

By resetting the value of #console before you itterate through the sortable children there will only be the current sortables in there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.