SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    71
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Getting the index position of a textarea selection.

    Hi all,

    I'm really struggling to find any sample code for getting the start and end position of a text area selection (i.e. a textarea contains the phrase "Why isn't there a standard, well-known function that does this?" and somebody selects the word "there" -- using a function, I'd like to be able to grab the start position and end position of the word "there").

    Can anybody help me with this, or am I going to have to hack together some long-winded function to do this seemingly simple task?

    Thanks in advance.

  2. #2
    SitePoint Enthusiast
    Join Date
    Jan 2006
    Posts
    28
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Heres a snippet of code:
    HTML Code:
     var txtarea = document.editform.wikitext;
    if(txtarea.selectionStart || txtarea.selectionStart == '0') {
     var replaced = false;
     var startPos = txtarea.selectionStart;
     var endPos   = txtarea.selectionEnd;
        if(endPos - startPos) replaced = true;
     var scrollTop=txtarea.scrollTop;
     var myText = (txtarea.value).substring(startPos, endPos);
    if(myText.charAt(myText.length - 1) == " "){ // exclude ending space char, if any
          subst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " ";
       } else {
      myText = myText.replace(/link:/g,'');
    
          subst =  '<a href="'+sponsurl+'">'+myText+'</a>';
          
        }
        txtarea.value = txtarea.value.substring(0, startPos) + subst +
                        txtarea.value.substring(endPos, txtarea.value.length);


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •