[英]how to submit highlighted text from textarea into database
I have to save highlighted text from textarea into database on click event how can i do it. 我必须在点击事件中将突出显示的文本从textarea保存到数据库中,我该怎么做。 I found some code from so but it doesn't work for me.
我从中找到了一些代码,但对我不起作用。
$('#send').on("click", function(){ ShowSelection(); }); function ShowSelection() { var textComponent = $('#my-content span').val(); console.log(textComponent); var selectedText; if (textComponent.selectionStart !== undefined) {// Standards Compliant Version var startPos = textComponent.selectionStart; var endPos = textComponent.selectionEnd; selectedText = textComponent.value.substring(startPos, endPos); } else if (document.selection !== undefined) {// IE Version textComponent.focus(); var sel = document.selection.createRange(); selectedText = sel.text; } alert("You selected: " + selectedText); }
There is a lot wrong with your code: 您的代码有很多错误:
selectionStart
and selectionEnd
are properties of form elements (input, textarea), but $('#my-content span')
is obviously finding a <span>
element. selectionStart
和selectionEnd
是表单元素(输入,文本区域)的属性,但是$('#my-content span')
显然在查找<span>
元素。
$('#my-content span').val()
will return a string (in the case of an input it's the value of that input, but in your case it will be empty, because you apply it on a span element. $('#my-content span').val()
将返回一个字符串(在输入的情况下,它是该输入的值,但在您的情况下,它将为空,因为您将其应用于span元素。
textComponent.selectionStart
: Since textComponent
is a string and not an HTML element there is no property selectionStart
on textComponent
. textComponent.selectionStart
:由于textComponent
是字符串而不是HTML元素,因此textComponent
上没有属性selectionStart
。
-- -
Working example for a <textarea>
element ( see here ): <textarea>
元素的工作示例( 请参见此处 ):
var startPos = $('textarea')[0].selectionStart
// etc.
Working example for <span>
element ( see here ): <span>
元素的工作示例( 请参见此处 ):
var selectedText = window.getSelection().toString()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.