1

I am trying to implement a function that let me drag and drop a list of elements into a matrix.

The first step that I am trying right now is to simple drag one element into an area. It do it right on the first element but the second and the others don't.

Code

I have the next JavaScript code:

var dragSrcEl = null;

function dragStart(event) {
    event.dataTransfer.setData("Text", event.target.id);
}

function dragEnter(event) {
    if ( event.target.className == "droptarget" ) {
        document.getElementById("demo").innerHTML = "Entered the dropzone";
        event.target.style.border = "3px dotted red";
    }
}

function dragLeave(event) {
    if ( event.target.className == "droptarget" ) {
        document.getElementById("demo").innerHTML = "Left the dropzone";
        event.target.style.border = "";
    }
}

function allowDrop(event) {
    event.preventDefault();
}

function drop(event) {
    event.preventDefault();
    var data = event.dataTransfer.getData("Text");
    event.target.appendChild(document.getElementById(data));
}

And the HTML is using this by doing the next code:

...
            <div class="input-group input-group-option col-xs-12" ondragstart="dragStart(event)" draggable="true" id="dragtarget">
              <span class="input-group-addon" id="sizing-addon2">1</span>
              <input type="text" name="option[]" class="form-control" placeholder="Focus me">
              <span class="input-group-addon">
                <span class="glyphicon glyphicon-align-justify"></span>
              </span>
            </div>

            <div class="input-group input-group-option col-xs-12" ondragstart="dragStart(event)" draggable="true" id="dragtarget">
              <span class="input-group-addon" id="sizing-addon2">2</span>
              <input type="text" name="option[]" class="form-control" placeholder="Focus me">
              <span class="input-group-addon">
                <span class="glyphicon glyphicon-align-justify"></span>
              </span>
            </div>

            <div class="input-group input-group-option col-xs-12" ondragstart="dragStart(event)" draggable="true" id="dragtarget">
              <span class="input-group-addon" id="sizing-addon2">3</span>
              <input type="text" name="option[]" class="form-control" placeholder="Focus me">
              <span class="input-group-addon">
                <span class="glyphicon glyphicon-align-justify"></span>
              </span>
            </div>
...

How can I Drag and Drop more then one element?

JSFiddle

Francisco Maria Calisto
  • 2,841
  • 4
  • 22
  • 54

1 Answers1

1

Please Try this one:

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    if (ev.target.childNodes.length === 0) {
        ev.target.appendChild(document.getElementById(data));
    }    
}

Demo below here:

DEMO

DEMO 1

Community
  • 1
  • 1
Ivin Raj
  • 3,448
  • 2
  • 28
  • 65