Unable to Drop on an Empty List - javascript

I am making a simple web app. At one part I have to drag among two different lists - One of which may be empty. I am not able to drop to an empty list.
I have tried:
dropOnEmpty = true
dropOnEmpty = "true"
dropOnEmpty = false
dropOnEmpty = "false"
and tried stuff as on:
How do I move an item to an empty list using jquery?
JQuery API
Rollys Wordpress
jQuery UI drop on empty container/list not working
Hidden <li> elements so that lists are not empty at all.
but nothing worked.
This is the HTML part:
<ul><li>Present</li></ul>
<ul id="present" class="sortable"></ul> //First List
<ul><li>Future</li></ul>
<ul id="future" class="sortable"><li></li></ul> //Second List
This is the jQuery function:
$("ul.sortable").sortable({
axis: 'y',
cancel: "div.cal",
connectWith: "ul",
dropOnEmpty: true,
update: function(event, ui) {
if (ui.sender === null) {
var goalsNames = '';
$(".sortable li").each(function() {
if (goalsNames === '') {
goalsNames = '["' + $(this).text();
} else {
goalsNames += '","' + $(this).text();
}
});
goalsNames += '"]';
localStorage.setItem("goalsNames", goalsNames);
var goalsDetails = localStorage.getItem("goalsDetails");
console.log(goalsDetails);
var goalsDetailsObj = JSON.parse(goalsDetails);
$("#present li").each(function() {
console.log(JSON.stringify(goalsDetailsObj[$(this).text()]));
console.log(goalsDetailsObj[$(this).text()].active);
goalsDetailsObj[$(this).text()].active = "present";
});
$("#future li").each(function() {
goalsDetailsObj[$(this).text()].active = "future";
});
localStorage.setItem("goalsDetails", JSON.stringify(goalsDetailsObj));
}
}
}).disableSelection();
});

As far as I know, sortable is a JQuery-UI feature to sort items within one list via drag and drop.
From the docs
Enable a group of DOM elements to be sortable. Click on and drag an element to a new spot within the list
I would try to go with draggable and droppable and you need to initialize a drop target via droppable.
<ul><li>Present</li></ul>
<ul id="present" class="firstList"></ul> <!--First List-->
<ul><li>Future</li></ul>
<ul id="future" class="secondList"><li></li></ul> <!--Second List-->
$('ul.firstList').draggable(/***/);
$('ul.secondList').droppable(/***/);
And read about the many options to be inserted at /***/.
Update
I created a plunker for you as a start point: http://plnkr.co/RPlTgK

Here is the proper example for drag and drop among empty list hope this will help Demo

Related

jquery drag multiple table rows with sortable

i have 2 tables and i need to select some rows from one, then drop them to the other table in the position i want to place.
i can drag multiple rows, but they will be placed on the end of table..i need to place where i want.
i tried with this
$("#table1 .childgrid tr, #table2 .childgrid tr").draggable({
helper: function(){
var selected = $('.childgrid tr.selectedRow');
if (selected.length === 0) {
selected = $(this).addClass('selectedRow');
}
var container = $('<div/>').attr('id', 'draggingContainer');
container.append(selected.clone().removeClass("selectedRow"));
return container;
}
});
http://jsfiddle.net/83k9k/5/
but i can't apply the sortable.
here i tried to apply sortable, but i can't apply the selected rows.
$("#table1 .childgrid, #table2 .childgrid").sortable({
connectWith: ".childgrid",
//connectWith: ".t_sortable",
items: $(".draggable_tr"),
//items: "> tr:not(:first)",
appendTo: $tabs,
//helper:"clone",
zIndex: 999990,
helper: function(){
var selected = $('.childgrid tr.selectedRow');
if (selected.length === 0) {
selected = $(this).toggleClass('selectedRow');
}
console.log(selected.length)
var container = $('<div/>').attr('id', 'draggingContainer');
//console.log(container)
container.append(selected.clone().removeClass("selectedRow"));
return container;
},
update: function (event, ui)
{
$(this).append(ui.helper.children());
$('.selectedRow').remove();
}
}).disableSelection();
http://jsfiddle.net/ce36vd0h/
where is the issue?
Please check below. I have made some changes. THe problem I see is , you are dragging inside a table, so you do not get which tr you are dragging after . I have made below changes. I have added a class tt1 in every table row on the right side table. And then called the droppable in the table row instead of the table itself. You can do the same for the left table. This just show the example. I am not sure if this goes with your actual usecase but I feel this is the best way to identify the table row where you are dropping. I am not sure about the sortable, are you trying to apply sortable after the row is moved ?
http://jsfiddle.net/2gb7vcLf/
$("#table1 .childgrid, #table2 .tt1").droppable({
drop: function (event, ui) {
// alert($(this).hasClass('childgrid'))
//alert($(this).closest('tr').hasClass('draggable_tr'))
var droppedRow = $(this).closest('tr');
// $(droppedRow).css('color', 'red');
$(ui.helper.children()).insertAfter(droppedRow);
// $(droppedRow).next(ui.helper.children());
//$(this).append(ui.helper.children());
$('.selectedRow').remove();
}
});
<tr class="draggable_tr tt1">

Kendo ListBox: Return dropped items in order

I am using two listboxes, connected with each other, that allow drag and drop between the two. While using the reorder code found in another thread fixes the issue with reordering items within the same list, it doesn't address the issue when dragging and dropping an item from one listbox to the other. I understand that is because this isn't a "reorder" action, it is a "drop" action. I've tried many different angles, like using the "add" event, but there is no "offset" property in the (e) object.
How can I accomplish the same thing, that is, keep the dropped item in the order it is visually dropped?
Here is my widget function with the reorder event that properly orders the items as they are displayed in the listBox (why this doesn't happen automatically is beyond me!). Remember, the reorder event only occurs when moving items within the same listBox, not when dragging an item from one listBox to another.
$("#myMenus").kendoListBox({
draggable: true,
connectWith: "baseMenus",
dropSources: ["baseMenus"],
add: function(e) {
console.log('ADD');
console.log(e);
},
reorder: function(e) {
e.preventDefault();
var dataSource = e.sender.dataSource;
var dataItem = e.dataItems[0];
var index = dataSource.indexOf(dataItem) + e.offset;
dataSource.remove(dataItem);
dataSource.insert(index, dataItem);
},
});
I've managed to accomplish the same task, depending on the html hint that appears while dropping the item in the second listbox. I've modified your code with the solution.
$("#myMenus").kendoListBox({
draggable: true,
connectWith: "baseMenus",
dropSources: ["baseMenus"],
add: function(e) {
e.preventDefault();
var dataSource = e.sender.dataSource;
var dataItem = e.dataItems[0];
var index = $('li.k-drop-hint').index();
dataSource.insert(index, dataItem);
},
reorder: function(e) {
e.preventDefault();
var dataSource = e.sender.dataSource;
var dataItem = e.dataItems[0];
var index = dataSource.indexOf(dataItem) + e.offset;
dataSource.remove(dataItem);
dataSource.insert(index, dataItem);
},
});

How to find previously dropped value from droppable div

I am working on dynamic formula generator using jquery drag and drop functionlaity
What i have done so far is
I have two 2 list
<ul id="head">
<li class="horizontal">Salary</li>
<li class="horizontal">Workers</li>
<li class="horizontal">Perday</li>
</ul>
and
<ul id="operations">
<li class="horizontal">Add +</li>
<li class="horizontal">Sub -</li>
<li class="horizontal">Multiply *</li>
<li class="horizontal">Divide /</li>
</ul>
The process is user will first drag from first list and drop in droppable div and they will add anything from operations list like (+,- etc..).
The Jquery i have used :
$('#head li').draggable({
cursor: 'move',
helper: 'clone',
connectToSortable: "#drop",
});
$("#drop").droppable({
drop: function (event, ui) {
$(this)
.removeClass("ui-droppable ui-sortable")
.addClass("horizontal ui-draggable ui-draggable-handle")
}
}).sortable();
droppable div
<div id="drop" style="border:2px solid;min-height:100px;"></div>
My Problem is that i have to validate user should not drop more than one operations at a time. ex:Multiply * Add + this is wrong. The operations must come between 2 text. so how i can we find the previously added value in this droppable div (drop).
Thanks in advance
How about using some data attribiutes to id your operations and a variable in js to store what was dropped last, like this:
HTML
<div class='js-droppable' data-drop-type='op'>operation 1</div>
JS
var lastDropped = '';
var processDroppable = function () {
var dropped = $(this).data('drop-type');
if (lastDropped == 'op' && dropped == 'op') {
console.log('not allowed')
} else {
console.log('you may drop ...');
}
lastDropped = dropped;
}
$('.js-droppable').click(processDroppable);
The data attribute stores the type of droppable and then is used to catch any duplicate droppable that is not allowed.
You could do any logic really based on identifying your droppables, but lastDropped == 'op' && dropped == 'op' covers the case in the question.
The working example is here in JSFiddle, I've used click events rather than dropped events, for simplicity; open the console to see the output.

Add dynamic list items to dynamically created panel with a istview

I'am using jquery mobile 1.3.2 for my web project.
The following code creates a panel for all pages:
function injectPanelIntoAllPages(){
console.log("IncetPanel");
var panel = '<div data-role="panel" id="mypanel" data-position="left" data-display="push">' +
'<div><ul data-role="listview" id="history"></ul></div> </div>';
$(document).on('pagebeforecreate', '[data-role=page]', function () {
if ($(this).find('[data-role=panel]').length === 0) {
$('[data-role=header]').before(panel);
}
$(document).on('pagebeforeshow', '[data-role=page]', function () {
$(this).trigger('pagecreate');
});
});
}
Now i want to add (dynamically) list items to the listview in the panel, but it don't works.
For adding list items i use the following method:
function addToHistory(value) {
$("#history").append(
"<li id='history-element'>" + value + "</li>");
$("#history").listview("refresh");
}
What can i do to solve this issue?
Note that you're using same Id for both panel and listview. This isn't recommended, however, it still can work as long as you specify which element to target within active page.
Another note, you don't need to call any enhancement method once you append panels dynamically, since you append them on pagebeforecreate. They will be created/initialized by jQM on that event.
$(document).on('pagebeforecreate', function () {
if ($(this).find('[data-role=panel]').length === 0) {
$('[data-role=header]').before(panel);
}
});
To append elements into listview, you need to look for it into active page's. Otherwise, new elements will be added to first element with #history ID.
var listview = $.mobile.activePage.find("#history");
listview.append("elements").listview("refresh");
Demo

How to build a Drag and Drop Menu Builder?

Hi all i present i am wokring on Menu Builder,where user can come build his menu how ever he likes with the subemnus to,i have a problem in Drag and Drop, i had done till drag but drop is not working in my case
i have to achevie some thing like this
http://www.prodevtips.com/demos/drag_drop_tree/
but not similar i should be able to create a chain or tree with drag and drop,my scenario is i have all menus listed at the bottom and and add column button at the top,when user wants to build menu he can click on addmenu button and a column opens there he can drag and drop the menus from the listed menu, from here i want the working scenario of the above link i had given where if i drop on any menu item it should be the child of that parent menu item which the user dropped on
here is my script
$(document).ready(function() {
var i = 0;
$("button[id='columnadd']").click(function () {
alert(1);
var domElement = $('<aside id="shoppingCart' + i + '" class="shoppingCart"><h2 class="ui-widget-header">Add Menu Items Here</h2><aside class="ui-widget-content"><ol><li class="placeholder">Add your items here</li></ol></aside></aside>');
i++;
$(this).after(domElement);
});
$(".small_box li" ).draggable({
appendTo: "body",
helper: "clone"
});
});
$(".small_box li a").droppable({
tolerance : "pointer",
hoverClass : "tree_hover",
drop : function(event, ui){
var dropped = ui.draggable;
dropped.css({top: 0, left: 0});
var me = $(this).parent();
if(me == dropped)
return;
var subbranch = $(me).children("ul");
if(subbranch.size() == 0) {
me.find("a").after("<ul></ul>");
subbranch = me.find("ul");
}
var oldParent = dropped.parent();
subbranch.eq(0).append(dropped);
var oldBranches = $("li", oldParent);
if (oldBranches.size() == 0) { $(oldParent).remove(); }
}
});
and here is my html
<body>
<button id="columnadd" >Add Column</button>
<aside class="menu-structer" id="AddColumns" >
</aside>
<aside class="small_box">
<h4>BRANDS</h4>
<ul>
<li id ="brand1"><a class="" href="#">Brand1</a></li>
<li id ="brand2">Brand2</li>
<li id ="brand3">Brand3</li>
<li id ="brand4">Brand4</li>
</ul>
</aside>
<aside class="small_box">
<h4>CATEGORIES</h4>
<ul>
<li id ="category1">Category1</li>
<li id="category2">Category2</li>
<li id="category3">Category3</li>
<li id="category4">Category4</li>
</ul>
</aside>
<aside class="small_box">
<h4>PRODUCTS</h4>
<ul>
<li id="Product1">Product1</li>
<li id="product2">Product2</li>
<li id="product3">Product3</li>
<li id="product4">Product4</li>
</ul>
</aside>
</body>
can any one help me over here please...that would be of a a great help for me..i am struggling with the Drop Event
Mistakes i had done
I had created a DOM Element (which is the drop area) upon click and this element is not in your page until you click the trigger. By doing $('#shoppingCart ol').droppable({...}) in $(document).ready(function() {}) block you try to add droppable to an element that even not in your page, so this won't do a thing.
changes
What i had done is make the element droppable after create that element
$("button[id='columnadd']").click(function () {
// create the element
var domElement = $('<aside id="shoppingCart' + i++ + '" class="shoppingCart"><h2 class="ui-widget-header">Add Menu Items Here</h2><aside class="ui-widget-content" id="droppable"><ol><li class="placeholder">Add your items here</li></ol></aside></aside>');
// put it after $(this)
$(this).after(domElement);
// at this point you have domElement in your page
// make it droppable
domElement.find("ol").droppable({
// put options here
greedy: true,
drop: function (event, ui) {
makeItDroppableToo(event, ui, this);
}
});
});
and this is the function to make your dropped element has its own placeholder
function makeItDroppableToo(e, ui, obj) {
$(obj).find(".placeholder").remove();
var placeholder = $("<ol><li class='placeholder'>You can also drop it here</li></ol>");
$("<li></li>").append(ui.draggable.text()).append(placeholder).appendTo($(obj));
// this is the same as the previous one
placeholder.droppable({
// put options here
greedy: true,
drop: function (event, ui) {
makeItDroppableToo(event, ui, this);
}
});
}

Categories