title: How to re-select the selected text in textarea by using javascript/jQuery?
body: <p>I'm using javascript and jQuery to design a comment box.</p>
  
  <p>My page has a <code>textarea</code> and 3 buttons (bold, underline and italic). If a user types text in the textarea, selects and clicks any button, the selected text should become <em>bold</em>, <em>underlined</em> or <em>italicised</em> (I have this functionality below).</p>
  
  <p>My problem is that after clicking a button with text selected, although the html tags are correctly inserted, the selection is lost. That is, when I type: "Hello, I'm here.", select "I'm here" and click the <em>bold</em> button. <strong>I'm here</strong> becomes bold but if I want to also <em>underline</em> or <em>italicise</em>, I have to reselect the text.</p>
  
  <p>So, my question is: How do I re-select the selected text in the <code>textarea</code>?</p>
  
  <p>I tried <code>myTextarea.select()</code> but this code will select the entire contents of the <code>textarea</code>, not only the selected text.</p>
  
  <p><strong>Update:</strong></p>
  
  <p>Here is what I've got so far:</p>
  
  <pre><code>var mystring = ""; // default string
  
  /* Bold event */
  function Bold()
  {
    var startString;
    var endString;
    var startPos; // starting position
    var endPos; // ending position
    var selectedText;
    var temp = document.getElementById("myTextarea");
  
    // check if text is selected
    if(temp.selectionStart !== undefined)
    {
      startPos = temp.selectionStart;
      endPos = temp.selectionEnd;
      selectedText = temp.value.substring(startPos, endPos);
      startString = temp.value.substring(0, startPos);
      endString = temp.value.substring(endPos, temp.value.length);
    }
  
    $("#myTextarea").val(startString + "[B]" + selectedText + "[/B]" + endString); // rewrite textarea value
  
    if(mystring !== "") // check if default string is NOT null, return null if it's the first clicked
    {
      mystring = mystring.replace(selectedText, "&lt;b&gt;" + selectedText + "&lt;/b&gt;");
    }
    else
    {
      mystring = startString + "&lt;b&gt;" + selectedText + "&lt;/b&gt;" + endString;
    }
  
    // write to preview panel
    $("#preview").html(mystring);
    $("#myTextarea").focus();
  }
  </code></pre>
  
  <p>When I select "I'm here" in the <code>textarea</code> and click the bold button the code above will insert <code>[B]</code> and <code>[/B]</code> into the <code>textarea</code> and <code>&lt;b&gt;</code> tags into the preview panel.</p>