0

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);
 }
joe
  • 29
  • 1
  • 1
  • 6

1 Answers1

0

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()
user1521685
  • 210
  • 2
  • 13