views:

8819

answers:

5

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?

+2  A: 

I thins you should look to selectionstart/selectionend properties of the input field for firefox and textrange in IE some reference : http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/

Matthieu
A: 
mavera
A: 

For Opera, Firefox and Safari, you can do this and just call textarea.getSelection(). You can setup the same type of thing for HTMLInputElement. (Omit the newline normalization if you don't want it.)

HTMLTextAreaElement.prototype.getSelection = function() {
    var val = this.value.substring(this.selectionStart, this.selectionEnd);
    return val.replace(/\r\n|\r|\n/g, "\r\n");
};
Shadow2531
A: 

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?

mavera
+7  A: 

OK, here is the code I have:

function ShowSelection()
{
  var textComponent = document.getElementById('Editor');
  var selectedText;
  // IE version
  if (document.selection != undefined)
  {
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }
  // Mozilla version
  else if (textComponent.selectionStart != undefined)
  {
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    selectedText = textComponent.value.substring(startPos, endPos)
  }
  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...

PhiLho
Thanks a lot. It's work.
mavera