I'm creating an interface that allows the user to drag & drop preset responses into a "reply" <textarea>
. I decided to use jQuery UI.
The issue: After typing in the <textarea>
, the .droppable() functionality is broken.
I can click inside the <textarea>
and then drop text into it, but after typing, I can't drop any text into the <textarea>
...
jQuery:
$(document).ready(function(){
$(init);
// Initialization
function init(){
// Draggable
$(".response").draggable({
helper : "clone",
cursor : "move"
});
// Droppable
$(".survey-reply textarea").droppable({
accept : ".response",
drop : dropResponse
});
}
// When Dropped
function dropResponse(event,ui) {
var draggable = ui.draggable;
// Get existing text
var text = $(this).text();
// If field is empty then just apply the dragged response
if (text == "") {
$(this).text(draggable.children(".saved-response").val()).appendTo(this);
}
// If not, then add the dragged response to the present text
else {
$(this).text(text + ' ' + draggable.children(".saved-response").val()).appendTo(this);
}
}
});
This accomplishes what I need (almost). It allows me to drag the <li>
responses into a <textarea>
. It also compiles the text instead of replacing the text in the <textarea>
.
What it doesn't do: I need the user to be able to type in the <textarea>
, then drag a response into the <textarea>
, at which time the preset response is added to the typed text.
At the moment, I can click inside the <textarea>
, and while it is in focus, drag responses into it. But for some reason, typing in the <textarea>
disables the droppable event...
If anyone can help me figure out how to type in the text areas, then drag the responses into the same text area, I would be greatful!
Note: I didn't include the HTML, but I assure you, the selectors are accurate. I do have a placeholder attribute applied to the <textarea>
. I don't believe this has anything to do with the issue (since dragging and dropping the text eliminates the displayed placeholder text...
The problem is you're using the text()
function to get/set the textarea value, what you really want is val()
. Also, I don't think you want the .appendTo(this)
calls where you're updating the textarea value and you don't need to wrap your call to init with $()
, you can just do init();
. Change these two lines and it should work:
Change this:
var text = $(this).text();
to
var text = $(this).val();
and change this:
$(this).text(text + ' ' + draggable.children(".saved-response").val()).appendTo(this);
to this:
$(this).val(text + ' ' + draggable.children(".saved-response").val());