AndrewLeonardi AndrewLeonardi - 7 months ago 35
Javascript Question

Push dropped item to Array using jQuery UI?

I'm trying to push a word's ID to a list once it's dropped using jQuery UI's droppable feature. When I drag and drop the word the

console.log()
gives me the correct ID. However my
.push()
call below does nothing. How do I push the given ID?

Goal:

Before drop: One, Two,

After drop: One, Two, Three,

JavaScript:

var words = ["One,Two,"];
document.getElementById("demo").innerHTML = words.toString();

$(move);

function move() {
$('#moving').draggable();
$('#drop').droppable({
drop: handleDropEvent
});
}

function handleDropEvent(event, ui) {
var draggable = ui.draggable;
var droppable = ui.droppable;
var word = ui.draggable.attr('id')
words.push(word)
console.log(word)
$('#moving').hide(draggable.attr);
}


HTML:

<p id="demo"></p>

<div>
<span id="Three">
<strong> Three </strong>
</span>
</div>

Answer

The #demo element doesn't automagically update when you change the words variable. You have to manually update it:

var words = ["One,Two,"];
document.getElementById("demo").innerHTML = words.toString();

$(move);

function move() {
  $('#moving').draggable();
  $('#drop').droppable({
    drop: handleDropEvent
  });
}

function handleDropEvent(event, ui) {
  var draggable = ui.draggable;
  var droppable = ui.droppable;
  var word = ui.draggable.attr('id') 
  words.push(word)
  document.getElementById("demo").innerHTML = words.toString();
  console.log(word)
  $('#moving').hide(draggable.attr);
}
Comments