How to drag and drop <li> elements into input fields

eddy picture eddy · Aug 25, 2013 · Viewed 10.8k times · Source

I'm trying to develop a page that has the following functionality:

Page will have two columns: one being #origin(left column), containing a list of rectangles(which represent variables), and the second one will be #drop(right column),containing inputs where the rectangles can be dropped on.

enter image description here

In order to get the result I want , I'd thought of using two plugins: jquery ui draggable and jQuery Tokeninput

The question is , how can I make that once I drop a rectangle( <li> ) into an input field , it is displayed as a tag. It'd also be OK to use the same <li> element , so long I can enter more text into the input(to complete a formula) ,and if later the user changes its mind and decides that the variable (tag) was not the one he or she wanted, the page should allow them to delete the tag(by clicking the "X" in the top-right corner or returning the tag to its original location on the left column)

Has someone done something similar already and can give me some guidance?? Or has someone another idea for this?

Any help is greatly appreciated.

P.S. If you know of any other tagging plugin that lets combine text and tags in the same input please let me know.

Answer

Muhammad Umer picture Muhammad Umer · Aug 25, 2013

Take a look: Preview

This is my first time ever dealing with drop and drag seriously. And i kept going.

Lot can be improved. And made more efficent however, i have already spent like 3 hours on it :D.

I did learn a LOOOT.

$('.menu li').on('mousedown', function (e) {
    $(this).draggable({
        helper: "clone"
    }).css({
        opacity: '.7'
    });

});
var li = {}, i = 0;

function enable(x) {
    x.droppable({
        hoverClass: "drop-hover",
        drop: function (e, ui) {
            $(ui.draggable).clone().prependTo(this).draggable().addClass('special').data('i', $(this).data('i'));
            $(this).droppable('destroy')
        }
    });
};
$('.i1').each(function (u, n) {
    $(this).data('i', i);
    li[i] = $(this);
    i++;
});
$('.i1').each(function (u, i) {
    enable($(this));
});
$('.m').droppable({
    accept: ".special",
    drop: function (e, ui) {
        var x = $(ui.draggable).data();
        $(ui.draggable).remove();
        enable(li[x.i]);
    }
});


$('input[type="text"]').keypress(function (e) {
    if (e.which !== 0 && e.charCode !== 0) { // only characters
        var c = String.fromCharCode(e.keyCode | e.charCode);
        $span = $(this).siblings('span').first();
        $span.text($(this).val() + c); // the hidden span takes 
        // the value of the input
        $inputSize = $span.width();
        $(this).css("width", $inputSize); // apply width of the span to the input
    }
});