JQuery draggable revert based on condition

I have a problem with jQuery draggable and droppable. Here is a description of something I want to do.

First: I have two divs. One is <div id="selected"> and the other is <div id="container"> . The "container" has 10 <li> that are dragged and dropped into the "selected". Here is the code:

 <div id="selected"> <ul class="sortable-list"> </ul> </div> <div id="container"> <ul class="sortable-list"> <li>1</li> <li>2</li> <li>....</li> <li>9</li> <li>10</li> </ul> </div> 

Second: I want to allow any 5 <li> from the "container" to the "selected" div. If someone is trying to add the 6th <li> , then he should not let the user him. This 6th <li> , which will be inserted into the "selected", must be undone using the dragged jQuery parameter will return .

i.e. $("#container li").draggable({ revert: true }); Here is the javascript code for this.

 $(document).ready(function(){ var total = 0; $("#selected").droppable({ drop: function() { total = $("#selected li").length; //alert(total); if (total >= 5) { $("#container li").draggable({ revert: true }); } else { // below code is not working $("#container li").draggable({ revert: false }); // this is making whole feature weird. I can drag all the <li> anywhere } } }); }); 

This works fine.

Third: But when I drag the <li> from "selected" to "container", the "selected" div will only have 4 <li> s. Therefore, in this situation, later the user should be able to add another <li> to the "selected" div from the div "container". But, unfortunately, it does not work. All <li> that I am trying to drag to the "selected" ones are returned due to the if (total >= 5 ) condition if (total >= 5 ) .

Can someone help me solve this problem using the draggable revert option? You are welcome,...

+7
javascript jquery jquery-ui jquery-plugins
source share
2 answers

You can use the accept parameter, which executes the function much easier, for example:

 $("#selected ul").droppable({ accept: function() { return $("#selected li").length < 5; } }); 

You can check it out here . When you drag elements, .length goes down and it will accept elements again ... there is no reason to get complicated :)

+17
source share

First of all, setting revert to false will completely disable the return function. As you noticed, you can drop drag and drop anywhere. What you usually want is revert: 'invalid' , which means that it will be discarded whenever it falls on anything that is not droppable that accepts it.

What you want to do should be something like this:

 $('#selected').droppable({ drop: function() { // since you're doing a full re-calc every time, this doesn't need to be global var total = $("#selected li").length; if(total >= 5) { // once you've reached five, simply don't accept any more elements // the rest will revert if dropped here $('#selected').droppable('disable'); } } }); 
+3
source share

All Articles