Apurva Kulkarni
Apurva Kulkarni

Reputation: 55

Allow drag text and drop it in html input field without clearing previous data

I am working on Django application that require input field. The user can drag text and drop it in input field. But it clears the previously entered data . I want all typed and draggable text in input field. How can i achieve this?

<script type="text/javascript" >
{
  function allowDrop(ev) {
    ev.preventDefault();
  }

  function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
  }

  function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.value = $("#" + data).html();
  }

}

Upvotes: 1

Views: 6413

Answers (1)

weegee
weegee

Reputation: 3399

You cannot append data to an input field but you can take the old value and add to it. Get the value which is dragged by event.dataTransfer.getData('text'); and then add it with the old value like

var input = document.getElementById("test");
input.addEventListener('drop', function (event) {
    event.preventDefault();
    var textData = event.dataTransfer.getData('text'); // get the dragged value
    var oldval = event.target.value; // get the old value in the input
    var newval = oldval + textData; // add it with the value which is dragged upon
    event.target.value = newval; // change the value with the new value
});
document.querySelector('[draggable="true"]').addEventListener('dragstart', function(e){
  e.dataTransfer.setData('text', e.target.innerHTML);
});
<input id="test">
<p draggable="true">Some text</p>


Try dragging the value of the text onto the input
Also, no jquery is used.

Upvotes: 3

Related Questions