Adding a new item to a jquery sort that is not picked up by the update

I am sorting a list of objects, some of which are regular objects, and some of them are containers of other objects.

Sorting with the descriptor works fine, except when I add a new object to the container, it is not recognized after the update.

I have the following HTML:

<button>add another option</button> <div class="con"> <div class="ui-state-highlight"><span class="handle">handle</span> Item 1</div> <div class="ui-state-highlight"><span class="handle">handle</span> Item 2</div> <div class="ui-state-highlight"><span class="handle">handle</span> Item 3</div> <div class="subthing"> <span class="handle">handle</span> <div> <span class="handle">subhandle</span> subitem</div> <div> <span class="handle">subhandle</span> subitem</div> </div> </div> 

and script:

 $('button').click(function() { var x = $('<div class="ui-state-highlight"><span class="handle">handle</span> newthing</div>'); x.appendTo('.con') $(".con").sortable('refresh') }); var container = $(".con"); container.sortable({ handle: container.children().children(".handle") });​ 

Scenario

As you can see from the above code, if you add a new element, it cannot be sorted with the rest of the elements. I know if I say that the handle property has a .handle value, that it will do it, but I don't want the sub-handles to be part of the sortable.

+4
source share
4 answers

What you need:

 container.sortable({ handle: '> .handle' });​ 

Check this out: http://jsfiddle.net/hQsjD/

This is the> sign, which only captures the immediate child of the .handle.

It is important that the handle argument be a string selector, not the actual elements, because they will not be updated when the update is called.

+8
source

Here you go. You used the handle incorrectly:

 $('button').click(function() { var x = $('<div class="ui-state-highlight"><span class="handle">handle</span> newthing</div>'); x.appendTo('.con'); $(".con").sortable("refresh"); }); var container = $(".con"); container.sortable({ handle: ".handle" }); 

Fiddle

+2
source

Nothing worked for me, but this:

Instead:

 $(".selector").sortable('refresh'); 

I added the following:

 $(".selector").trigger("sortupdate"); 
+1
source

It seems to have decided: change

 $('button').click(function() { var x = $('<div class="ui-state-highlight"><span class="handle">handle</span> newthing</div>'); //My Edits x.appendTo('.con') var container = $(".con"); container.sortable({ handle: container.children().children(".handle") }); }); var container = $(".con"); container.sortable({ handle: container.children().children(".handle") }); 
-1
source

Source: https://habr.com/ru/post/1437673/


All Articles