Reputation: 453
I need someone to help me with jQuery draggable and droppable.
I don't understand why when I drap/drop the boxes show me 2 names for a item, though now I can use $.unique() but it is not practice at all. And I have try many ways but not sure how to pop values out of Like/Hate Array when items are taken out. Thank you very much!
Like = [];
Hate = [];
$(function () {
$("#AllTable .test").draggable({
appendTo: "body",
helper: "clone",
revert: "invalid",
});
$(".LikeBox div").droppable({
drop: function (event, ui) {
var $item = ui.draggable;
$item.appendTo("#likeTable");
var ingre = $item.text();
alert(ingre);
Like.push(ingre);
Like = $.unique(Like)
}
});
$(".HateBox div").droppable({
drop: function (event, ui) {
var $item = ui.draggable;
$item.appendTo("#hateTable");
var ingre = $item.text();
Hate.push(ingre);
Hate = $.unique(Hate)
}
});
$(function () {
$('.IngreMainCat').accordion();
});
});
Edit: My new code is this, problem 1 solved:
Like = [];
Hate = [];
$(function() {
$( "#AllTable .test" ).draggable({
appendTo: "body",
helper: "clone",
revert: "invalid",
});
$( ".LikeBox .droptrue" ).droppable({
drop: function( event, ui ) {
var $item = ui.draggable;
$item.appendTo("#likeTable");
var ingre = $item.text();
Like.push(ingre);
if($.inArray(ingre,Hate) > -1){
var index = Hate.indexOf(ingre);
if (index > -1) {
Hate.splice(index, 1);
}
}
}
});
$( ".HateBox .droptrue" ).droppable({
drop: function( event, ui ) {
var $item = ui.draggable;
$item.appendTo("#hateTable");
var ingre = $item.text();
Hate.push(ingre);
if($.inArray(ingre,Like) > -1){
var index = Like.indexOf(ingre);
if (index > -1) {
Like.splice(index, 1);
}
}
}
});
});
Upvotes: 0
Views: 973
Reputation: 17114
You actually have 2 divs that are droppable because of your selector. Since you call all child divs of .LikeBox
you get these 2 droppables that each run the drop function:
<div>
<div id="likeTable" class="droptrue">
After droppable is called it looks like this, see ui-droppable
on both:
<div class="ui-droppable">
<div id="likeTable" class="droptrue ui-droppable">
Clarify your selector and you shouldn't have the problem. Like this for example:
$( ".LikeBox .droptrue" ).droppable({
see working fiddle: https://jsfiddle.net/2ets9hjg/
EDIT:
For the elements to remove from your arrays, a suggestion: instead of using push
and pop
and keep track of what you add and remove in the tables, you can map
you tables when you need them. See jquery map: http://api.jquery.com/jquery.map/. It's easier to keep track that way. Like this:
Like = $.map($( "#likeTable div" ),function(a){return a.textContent});
https://jsfiddle.net/2ets9hjg/4/
Upvotes: 1