Reputation: 12035
I am having an issue related jQuery draggable and droppable. Here is description something what I want to do.
First: I have two divs. One is <div id="selected">
and another is <div id="container">
. "container" has 30 <li>
which are draggable and droppable into "selected". Here is 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>29</li>
<li>30</li>
</ul>
</div>
Second: I want to allow any 10 <li>
s from "container" to "selected" div. If someone tries to add 11th <li>
, then it must not allow user to it. That is the 11th <li>
that is going to be inserted into "selected" must be reverted using jQuery draggable option revert.
i.e. $("#container li").draggable({ revert: true });
Here is javascript code for that.
$(document).ready(function(){
var total = 0;
$("#selected").droppable({
drop: function() {
total = $("#selected li").length;
//alert(total);
if (total >= 10) {
$("#container li").draggable({ revert: true });
} else {
//$("#container li").draggable({ revert: false });
}
}
});
});
This is working fine.
Third: But when I drag an <li>
from "selected" to "container", the "selected" div will have only 9 <li>
s. So in this situation, later on user should be able to add another <li>
into "selected" div from "container" div. But unfortunately it is not working. All the <li>
s I try to drag and drop into "selected" are being reverted due to if (total >= 10 )
condition.
Can anyone help me to solve this out? Please...
Upvotes: 0
Views: 568
Reputation: 117354
I would suggest to use sortables, because its somehow the same like draggables and droppables on both div's.
It's not very diffcult with sortables, there is an receive-event. Observe this event and count the li's inside #selected, if there are more than allowed, you are able to cancel the current sorting.
Fiddle: http://jsfiddle.net/doktormolle/K7kDz/
Upvotes: 1
Reputation: 4331
first - I believe you should be making the UL droppable instead of the DIV, otherwise you LIs will end up outside the UL (you can style the UL to fill the whole DIV, so it will still trigger the droppable part when an element is above it)
$("#selected ul.sortable-list").droppable({
......
});
second and third - you have the ELSE part where you're setting revert to false commented out... is that just for this example or did you forget the comment there? (which would be the cause why it doesn't work)
} else {
// $("#container li").draggable({ revert: false });
}
also - have you tried Firebug to check you REALLY don't have those LIs in the selected DIV once you drag them out?
Upvotes: 0