Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying Where To Focus Within Textarea

I have a textarea...

<textarea>
Some writing here
*
Then some more on another line
</textarea>

What I want to do is focus the user where the * is. Is this possible?

like image 576
Ben Shelock Avatar asked Oct 15 '25 15:10

Ben Shelock


1 Answers

Use the following function to set a selection within a textarea.

function setSelRange(inputEl, selStart, selEnd) { 
   if (inputEl.setSelectionRange) { 
     inputEl.focus(); 
     inputEl.setSelectionRange(selStart, selEnd); 
   } else if (inputEl.createTextRange) { 
     var range = inputEl.createTextRange(); 
     range.collapse(true); 
     range.moveEnd('character', selEnd); 
     range.moveStart('character', selStart); 
     range.select(); 
   } 
}
// From http://www.webmasterworld.com/forum91/4527.htm

So, in your case, you can search for the position of the * character and use that value in a call like this:

var pos = 17; // Set this to the position of the * character.
setSelRange(document.getElementById('textareaId'), pos, pos);
like image 169
James Skidmore Avatar answered Oct 17 '25 05:10

James Skidmore