Note that there are some explanatory texts on larger screens.

plurals
  1. POProgrammatically select text (like as done with a mouse) that matches string in a textarea element
    primarykey
    data
    text
    <p>Consider the following problem:</p> <p>Have a textarea like so:</p> <pre><code>&lt;textarea id="body" name="body"&gt;&lt;/textarea&gt; </code></pre> <p>Also have some simple JavaScript (jQuery) that inserts some new text into the textarea so a user can embed an image:</p> <pre><code>$('textarea').val($('textarea').val() + '[img]path to image file[/img]'); </code></pre> <p>The trick is to automatically highlight the text in between the <code>[img][/img]</code> tags after that text is inserted so the user can just copy and paste their image URL in quickly, instead of manually selecting, then copy and pasting.</p> <p>I've racked my brain and gone all over the internet trying to figure this out, and the best I could do was this popular StackOverflow question <a href="https://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse">Selecting text in an element (akin to highlighting with your mouse)</a> which only addresses the problem of selecting the text inside an ENTIRE element, which is not what is desired here. The problem is to select text that matches a certain string, in this case <code>path to image file</code>, so the user can just copy/paste. (not sure if this is the best way to do it, but that's what I thought of...).</p> <p>Is this possible? I'm guessing we're going to need <code>getSelection()</code> and <code>createRange()</code> but other than that I have no idea where to go... any JavaScript wizards figured this one out already? I feel like this could be a popular question. Using jQuery is fine, as I'm already using it on the rest of the document.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload