问题
I need to create a message template as follows,
Hello Stackoverflow {Text A} Thank you for your support {Text B}
In that case, I need to use drags and drop fields to Textarea
, I did initial R&D to find some library to achieve my requirement and found this Inserting text with drag n’ drop
$(document).ready( function() {
$('#ClickWordList li').click(function() {
$("#txtMessage").insertAtCaret($(this).text());
return false
});
$("#DragWordList li").draggable({helper: 'clone'});
$(".txtDropTarget").droppable({
accept: "#DragWordList li",
drop: function(ev, ui) {
$(this).insertAtCaret(ui.draggable.text());
}
});
});
$.fn.insertAtCaret = function (myValue) {
return this.each(function(){
//IE support
if (document.selection) {
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
//MOZILLA / NETSCAPE support
else if (this.selectionStart || this.selectionStart == '0') {
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos)+ myValue+ this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
});
};
Html
<body>
<div id="maincontainer">
<div id="navtoplistline"> </div>
<div id="contentwrapper">
<div id="maincolumn">
<div class="text">
<h2>Message #1</h2>
<textarea name="txtMessage" id="txtMessage" class="txtDropTarget ui-droppable" cols="80" rows="15"></textarea>
<h2>Message #2</h2>
<textarea name="txtMessage2" id="txtMessage2" class="txtDropTarget ui-droppable" cols="80" rows="15"></textarea>
</div>
</div>
</div>
<div id="leftcolumn">
<fieldset>
<legend>Click to insert:</legend>
<ul id="ClickWordList">
<li>Hello world!</li>
<li>All your base</li>
<li>Lorem ipsum dolor sit amet...</li>
</ul>
</fieldset>
<fieldset>
<legend>Drag to insert:</legend>
<ul id="DragWordList">
<li class="ui-draggable">Hello world!</li>
<li class="ui-draggable">All your base</li>
<li class="ui-draggable">Lorem ipsum dolor sit amet...</li>
</ul>
</fieldset>
</div>
</div>
</body>
This works fine, but I only need to click the field and add clicked item to Textarea
(no need drag and drop option), and also need to remove added filed from Textarea by clicking cross sign. How can I do it, please help me to solve this. The above example is not clear for me to implement my requirement. so please help me to solve this.
Update: As Twisty says cannot implement X
inside Textarea what can I use instead of it? any suggestion?
来源:https://stackoverflow.com/questions/58156092/how-drag-and-drop-text-using-jquery