开发者

JQuery .change() function within .each() function

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


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);
        }
    }); 
});


$('#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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜