Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

html - How to get selected text from textbox control with javascript

I have a textbox and a link button. When I write some text, then select some of them and then click the link button, selected text from textbox must be show with a messagebox.

How can I do it?


When I click the submit button for textbox below, message box must show Lorem ipsum. Because "Lorem ipsum" is selected in the area.


If I select any text from the page and click the submit button it is working, but if I write a text to textbox and make it, it's not. Because when i click to another space, selection of textbox is canceled.

Now problem is that, when i select a text from textbox and click any other control or space, text which is selected is must be still selected.

How it is be done?

question from:https://stackoverflow.com/questions/275761/how-to-get-selected-text-from-textbox-control-with-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

OK, here is the code I have:

function ShowSelection()
{
  var textComponent = document.getElementById('Editor');
  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);
}

Problem, although the code I give for IE is given on lot of sites, I cannot make it work on my copy of IE6 on my current system. Perhaps it will work for you, that's why I give it.
The trick you look for is probably the .focus() call, to give back to textarea the focus so the selection is re-activated.

[UPDATE] I got the right result (the selection content) with onKeyDown event:

document.onkeydown = function (e) { ShowSelection(); }

So the code is correct. Again, the issue is to get the selection on click on a button... I continue to search.

[UPDATE] I got no success with a button drawn with a li tag, because when we click on it, IE deselects the previous selection. The above code works with a simple input button, though...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...