简体   繁体   中英

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. 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.

$('#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.

textComponent.selectionStart : Since textComponent is a string and not an HTML element there is no property selectionStart on textComponent .

--

Working example for a <textarea> element ( see here ):

    var startPos = $('textarea')[0].selectionStart
    // etc.

Working example for <span> element ( see here ):

    var selectedText = window.getSelection().toString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM