Noor Noor - 6 months ago 30
jQuery Question

JQuery UI dragable tags

My requirement is that there should be tags in a container, and user can drag tags and drop in the input field. How to maintain the dropped tag as tag and not as text.

I tried this plugin, when I drag a tag and drop in the input field for the first element it works fine but for the second tag, it create total new container, and after adding second tag then another tag can not be added.
Here is the code,

<ul id="draggable">
<li>Tag1</li>
<li>Tag2</li>
<li>Tag3</li>
<li>Tag4</li>
</ul>

<p id="topdropped">
<input id="tags_1" type="text" class="tags" value="" />
</p>

$(function() {
$("#draggable li").draggable({
helper : 'clone'
});
$("#topdropped").droppable({
drop : function(event, ui) {

$(this).find("#tags_1").val(ui.draggable.text());
$('#tags_1').tagsInput({
width : 'auto'
});
}
});
});


Live demo

Answer

I solve this problem like this, here is the demo that I was want to achieve.

Before the problem was, I was calling and initiating plugin in the dropable, like this

 $('#tags_1').tagsInput({
      width : 'auto'
   });

Later I found that this plugin also provide addTag() method then I call this method on dropable and this solve my problem instead of above code I do like this.

if ($('#tags_1').tagExist(ui.draggable.text())) {
    alert("Already Added.");
    }else {
    $('#tags_1').addTag(ui.draggable.text());
    }

here the $('selector').tagExist() which is also provided by plugin check if the tag alread exist in the input field.

This is the code which is working.

<ul id="draggable">
    <li>Tag1</li>
    <li>Tag2</li>
    <li>Tag3</li>
    <li>Tag4</li>
</ul>

<p id="topdropped">
    <input id="tags_1" type="text" class="tags" value="" />
</p>


<script type="text/javascript">
    $(function() {
        $('#tags_1').tagsInput({
            'defaultText' : '',
            width : 'auto',
            'interactive' : true,
        });
        $("#draggable li").draggable({
            helper : 'clone'
        });
        $("#topdropped").droppable({
            drop : function(event, ui) {                    
                if ($('#tags_1').tagExist(ui.draggable.text())) {
                    alert("Already Added.");
                }else {
                    $('#tags_1').addTag(ui.draggable.text());

                }
            }
        });
    });
</script>