javascript - order list using sortable with id shown in each item using jquery -
i have following code:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>jquery test</title> <link rel="stylesheet" href="css/jquery_ui.css"> <script src="js/jquery-1.10.2.js"></script> <script src="js/jquery-ui.js"></script> <script src="js/functions.js"></script> <link rel="stylesheet" href="css/style.css"> </head> <body> <div class="container"> <ul id="sortable" class="ui-sortable"> <li id="1" class="ui-state-default" >first - </li> <li id="2" class="ui-state-default" >second - </li> <li id="3" class="ui-state-default" >third - </li> <li id="4" class="ui-state-default" >fourth - </li> <li id="5" class="ui-state-default" >fifth - </li> </ul> </div>
and following javascript:
$(function() { $('#sortable').sortable({ //to prevent items moving around when draging containment: "parent", start : function(event, ui) { // initial position(index) of item var start_pos = ui.item.attr('id'); ui.item.data('start_pos', start_pos); }, update : function(event, ui) { var index = ui.item.index(); var start_pos=ui.item.attr('id'); //update html of moved item current index $('#sortable li:nth-child(' + (index + 1) + ')').appendto(index); if (start_pos < index) { //update items before re-ordered item for(var i=index; > 0; i--){ $('#sortable li:nth-child(' + + ')').appendto(i - 1); alert("start position = "+start_pos); alert("moved position: "+index); } } else { //update items after re-ordered item for(var i=index+2;i <= $("#sortable li").length; i++){ $('#sortable li:nth-child(' + + ')').appendto(i-1); } } }, axis : 'y' }); });
what want program sort items while displaying id next each item. example if item (fourth) moved item(first) id next fourth 1 , id next first 4.what error in code not displaying id
i've created fiddle code. after running observed following error in console:
uncaught typeerror: cannot read property 'createdocumentfragment' of undefined
the reason following line:
$('#sortable li:nth-child(' + (index + 1) + ')').appendto(index);
the code failing because trying append html element variable index (which numeric).
i've modified update function follows:
update: function (event, ui) { var index = ui.item.index(); var start_pos = ui.item.attr('id'); // iterate on <li> elements $.each($('#sortable li'), function (idx, item) { // extract text (e.g. 'first') var substringindex = $(item).html().indexof(' -') + 1; var html = $(item).html().substring(0, substringindex); // set new index depending on position in list $(item).attr('id', (idx + 1)); // update text on <li> element $(item).html(html + ' - ' + (idx + 1)); }); },
see here working fiddle
Comments
Post a Comment