Click to See Complete Forum and Search --> : How to set/get caret position of a textfield in IE?
macfreakz
08-05-2005, 01:14 AM
Hello,
I wonder how to get/set the caret position of a textfield.
I dont wanna paste something, but only set the caret position.
With firefox I can do this stuff:
textfield.startSelection = pos;
With IE I dont have a plan how to solve.
Thank you very much!
deep.dhyani
08-05-2005, 02:12 AM
here is Another code for setting caret position.
<form name="emp"><br><br>
<input type="text" name="f1">
<input type="text" name="f2" value="Hello">
</form>
<script>
window.onload=function(){
var tr = document.emp.f2.createTextRange();
tr.findText(document.emp.f2.value.substring(3,4));
tr.select();
}
</script>
I have searched all over for code like this, but found nothing suitable, so I rolled my own:
<html>
<body style="font-family: tahoma; font-size: 8pt;">
<script language="JavaScript">
/*
** Returns the caret (cursor) position of the specified text field.
** Return value range is 0-oField.length.
*/
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
// Return results
return (iCaretPos);
}
/*
** Sets the caret (cursor) position of the specified text field.
** Valid positions are 0-oField.length.
*/
function doSetCaretPosition (oField, iCaretPos) {
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// Create empty selection range
var oSel = document.selection.createRange ();
// Move selection start and end to 0 position
oSel.moveStart ('character', -oField.value.length);
// Move selection start and end to desired position
oSel.moveStart ('character', iCaretPos);
oSel.moveEnd ('character', 0);
oSel.select ();
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0') {
oField.selectionStart = iCaretPos;
oField.selectionEnd = iCaretPos;
oField.focus ();
}
}
</script>
<form name="blah">
Text Field: <input type="text" name="nameEdit" value="">
<input type="button" value="Get Caret" onClick="alert (doGetCaretPosition (document.blah.nameEdit));">
<hr size=1 noshade>
New Position: <input type="text" name="newPosValue" value="">
<input type="button" value="Set Caret" onClick="doSetCaretPosition (document.blah.nameEdit, parseInt (document.blah.newPosValue.value));">
</form>
</body>
</html>
This will allow you to get/set the caret (cursor) position within a text field. It does not work with <textarea> controls, but works great with <input type="text"> fields.
Tested in IE6 and FireFox 1.0.5
AJAXAvatar
07-05-2006, 02:44 AM
Hi,
There's a really good article at http://www.theblueform.com/Home/TheMakingOf.aspx that expands on this a little bit, and goes into detail as to how and why it works.
It's entitled "Getting/Setting the Selected Text (Caret Positions) within a Text Box in Internet Explorer and Firefox"
It's worth checking out their form-builder on The Blue Form website too as it does lots of clever DHTML/JavaScript and AJAX tricks!
firvin
08-08-2006, 05:31 AM
Is there any other similar way to set the cursor position back in contenteditable div??
a_fabre@hotmail
08-13-2007, 11:45 AM
My code:
<SCRIPT LANGUAGE=JAVASCRIPT>
function getCursorPos(textElement){
var cursorPos = -1;
if (textElement && textElement.createTextRange) {
var range = document.selection.createRange().duplicate();
range.setEndPoint('StartToEnd',range);
var start = document.body.createTextRange();
start.moveToElementText(textElement);
cursorPos = calcBookmark(range.getBookmark())-calcBookmark(start.getBookmark());
var rLen = 0;
do{
var BrLen = rLen;
rLen = newLine(textElement.value.substring(0,cursorPos + rLen + 1));
}while(BrLen!=rLen);
cursorPos += rLen;
}
return cursorPos;
}
function calcBookmark(bk){
return (bk.charCodeAt(0)-1)+(bk.charCodeAt(3)-1)*65536+(bk.charCodeAt(2)-1);
}
</SCRIPT>
<SCRIPT LANGUAGE=VBSCRIPT>
option explicit
function newLine(str)
dim nl, r
set nl = new RegExp
nl.global = true
nl.pattern = "\r\n"
set r = nl.Execute(str)
newLine = r.count
set r = nothing
set nl = nothing
end function
</SCRIPT>
hi pp... I´ve found this doGetCaretPosition() function in many foruns and tip sites and I´ve detected a "bug", more a caracteristic. The funcion aways return the END of the selection if you r using Internet Explorer and return aways the START of the selection if you r using Firefox.
Then I fixed this.
function doGetCaretPosition (ctrl) {
var CaretPos = 0;
// IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length - SelLength;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
sagetarian
11-09-2009, 06:52 AM
Hey all
I thought I'd give a little code snippet to help out :) this code snippet works for any element... input, textarea, div or p with contentEditable=true etc...
setCaretPos = function (obj, position) {
if (obj.setSelectionRange) {
obj.focus();
obj.setSelectionRange(position, position);
} else if (obj.createTextRange) {
var range = obj.createTextRange();
range.move("character", position);
range.select();
} else if(window.getSelection){
s = window.getSelection();
var r1 = document.createRange();
var walker=document.createTreeWalker(obj, NodeFilter.SHOW_ELEMENT, null, false);
var p = position;
var n = obj;
while(walker.nextNode()) {
n = walker.currentNode;
if(p > n.value.length) {
p -= n.value.length;
}
else break;
}
n = n.firstChild;
r1.setStart(n, p);
r1.setEnd(n, p);
s.removeAllRanges();
s.addRange(r1);
} else if (document.selection) {
var r1 = document.body.createTextRange();
r1.moveToElementText(obj);
r1.setEndPoint("EndToEnd", r1);
r1.moveStart('character', position);
r1.moveEnd('character', position-obj.innerText.length);
r1.select();
}
}
Hope it comes in handy
Regs
"Web Design South Africa" (http://netforge.co.za)
Walle
12-10-2009, 10:17 PM
I have searched all over for code like this, but found nothing suitable, so I rolled my own:
<html>
<body style="font-family: tahoma; font-size: 8pt;">
<script language="JavaScript">
/*
** Returns the caret (cursor) position of the specified text field.
** Return value range is 0-oField.length.
*/
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
// Return results
return (iCaretPos);
}
/*
** Sets the caret (cursor) position of the specified text field.
** Valid positions are 0-oField.length.
*/
function doSetCaretPosition (oField, iCaretPos) {
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// Create empty selection range
var oSel = document.selection.createRange ();
// Move selection start and end to 0 position
oSel.moveStart ('character', -oField.value.length);
// Move selection start and end to desired position
oSel.moveStart ('character', iCaretPos);
oSel.moveEnd ('character', 0);
oSel.select ();
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0') {
oField.selectionStart = iCaretPos;
oField.selectionEnd = iCaretPos;
oField.focus ();
}
}
</script>
<form name="blah">
Text Field: <input type="text" name="nameEdit" value="">
<input type="button" value="Get Caret" onClick="alert (doGetCaretPosition (document.blah.nameEdit));">
<hr size=1 noshade>
New Position: <input type="text" name="newPosValue" value="">
<input type="button" value="Set Caret" onClick="doSetCaretPosition (document.blah.nameEdit, parseInt (document.blah.newPosValue.value));">
</form>
</body>
</html>
This will allow you to get/set the caret (cursor) position within a text field. It does not work with <textarea> controls, but works great with <input type="text"> fields.
Tested in IE6 and FireFox 1.0.5
Hi
Hi
I know this topic is little old but anyone know how to get that caret position into a text filed? Instead on that alert message?
Walle
12-12-2009, 12:01 PM
Anyone?
need some help to get that caret position value into a simple text filed Instead of that popup alert. Anyone know how?
I am not a JavaScript programmer and don’t really know how i can fix this.
justinbarneskin
12-12-2009, 11:26 PM
I don't feel like deciphering all that has gone before so, what can I do to help with this? Just click anywhere in the textarea and then hit the button...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD><TITLE>Sa8-11pm57</TITLE>
<META http-equiv=Content-Type content="text/html; charset=UTF-8">
<STYLE type=text/CSS>
//* {margin:0; padding:0;}
</STYLE>
<META content="MSHTML 6.00.2900.2963" name=GENERATOR></HEAD>
<BODY scroll="auto">
<SCRIPT type="text/javascript">
function storeCaret(textEl){textEl.caretPos = document.selection.createRange().duplicate(); }
function insertAtCaret (textEl, text){ if (textEl.createTextRange && textEl.caretPos) {textEl.caretPos.text=text;} else{ alert('no carat'); } }
</SCRIPT>
<br>
<textarea id="tx" style="height:400px;width:400px" ONCLICK="storeCaret(this);" ONSELECT="storeCaret(this);" ONKEYUP="storeCaret(this);"><TABLE BORDER=1>
<TR>
<TD> a </TD><TD> b </TD><TD> c </TD><TD> d </TD><TD> e </TD>
</TR>
<TR>
<TD> f </TD><TD> g </TD><TD> h </TD><TD> i </TD><TD> j </TD>
</TR>
<TR>
<TD> k </TD><TD> l </TD><TD> m </TD><TD> n </TD><TD> o </TD>
</TR>
<TR>
<TD> p </TD><TD> q </TD><TD> r </TD><TD> s </TD><TD> t </TD>
</TR>
</TABLE></textarea>
<input type=button onclick="insertAtCaret(document.getElementById('tx'),'Caret was here')" value="!">
</BODY></HTML>
Walle
12-13-2009, 02:49 AM
I don't feel like deciphering all that has gone before so, what can I do to help with this?
This code belove made by m2pc:
<html>
<body style="font-family: tahoma; font-size: 8pt;">
<script language="JavaScript">
/*
** Returns the caret (cursor) position of the specified text field.
** Return value range is 0-oField.length.
*/
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
// Return results
return (iCaretPos);
}
/*
** Sets the caret (cursor) position of the specified text field.
** Valid positions are 0-oField.length.
*/
function doSetCaretPosition (oField, iCaretPos) {
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// Create empty selection range
var oSel = document.selection.createRange ();
// Move selection start and end to 0 position
oSel.moveStart ('character', -oField.value.length);
// Move selection start and end to desired position
oSel.moveStart ('character', iCaretPos);
oSel.moveEnd ('character', 0);
oSel.select ();
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0') {
oField.selectionStart = iCaretPos;
oField.selectionEnd = iCaretPos;
oField.focus ();
}
}
</script>
<form name="blah">
Text Field: <input type="text" name="nameEdit" value="">
<input type="button" value="Get Caret" onClick="alert (doGetCaretPosition (document.blah.nameEdit));">
<hr size=1 noshade>
New Position: <input type="text" name="newPosValue" value="">
<input type="button" value="Set Caret" onClick="doSetCaretPosition (document.blah.nameEdit, parseInt (document.blah.newPosValue.value));">
</form>
</body>
</html>
I need to get that caret position value into a simple text filed somehow but don’t know how. Instead of that popup alert. Is it possible? I guess it is something with onClick="alert (doGetCaretPosition (document.blah.nameEdit));">
justinbarneskin
12-13-2009, 04:47 AM
<html>
<body style="font-family: tahoma; font-size: 8pt;">
<script language="JavaScript">
/*
** Returns the caret (cursor) position of the specified text field.
** Return value range is 0-oField.length.
*/
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
// Return results
return (iCaretPos);
}
/*
** Sets the caret (cursor) position of the specified text field.
** Valid positions are 0-oField.length.
*/
function doSetCaretPosition (oField, iCaretPos) {
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// Create empty selection range
var oSel = document.selection.createRange ();
// Move selection start and end to 0 position
oSel.moveStart ('character', -oField.value.length);
// Move selection start and end to desired position
oSel.moveStart ('character', iCaretPos);
oSel.moveEnd ('character', 0);
oSel.select ();
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0') {
oField.selectionStart = iCaretPos;
oField.selectionEnd = iCaretPos;
oField.focus ();
}
}
</script>
<form name="blah">
Text Field: <input type="text" name="nameEdit" value="">
<input type="button" value="Get Caret" onClick="document.getElementById('where').value=doGetCaretPosition (document.forms[0].elements[0]);">
<input id="where">
<hr size=1 noshade>
New Position: <input type="text" name="newPosValue" value="">
<input type="button" value="Set Caret" onClick="doSetCaretPosition (document.blah.nameEdit, parseInt (document.blah.newPosValue.value));">
</form>
</body>
</html>
Walle
12-13-2009, 05:38 AM
Wow! That works god justinbarneskin. You did it amazing fast without any problem I se and thank you very much your help. Big thanks also to you m2pc.
Manoj dotnet
08-02-2010, 07:40 AM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Put slected value in textarea</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/CSS">
</style>
<meta content="MSHTML 6.00.2900.2963" name="GENERATOR">
</head>
<body scroll="auto">
<script type="text/javascript">
function storeCaret(textEl){textEl.caretPos = document.selection.createRange().duplicate(); }
function insertAtCaret (textEl, text){ if (textEl.createTextRange && textEl.caretPos) {textEl.caretPos.text=text;} else{ alert('no carat'); } }
function insertCode()
{
var subject=document.getElementById('myTextarea');
if (document.selection)
{
insertAtCaret(document.getElementById('myTextarea'),'[' + document.getElementById('selectList').value + ']' );
}
else if (subject.selectionStart || subject.selectionStart=='0')
{
var str=subject.value;
var a=subject.selectionStart, b=subject.selectionEnd;
subject.value=str.substring(0,a)+arguments[0]+(arguments[1]?str.substring(a,b)+arguments[1]:"")+str.substring(b, str.length);
return;
}
};
function insertText()
{
var inp=document.getElementById('selectList');
insertCode('[' + inp.value + ']');
}
</script>
<br>
<textarea id="myTextarea" style="height: 200px; width: 300px" onclick="storeCaret(this);"
onselect="storeCaret(this);" onkeyup="storeCaret(this);"></textarea>
<br />
<select id="selectList">
<option value="delhi">Delhi</option>
<option value="jaipur">Jaipur</option>
<option value="Kolkata">Kolkata</option>
</select>
<input type="button" value="Insert Text" onclick="insertText();">
</body>
</html>
hendrik.kroon
09-14-2010, 03:42 PM
Dear all,
First of all, thank you all for this topic so far.
I have tried the Get / Set caret functions, and they work fine.
but i want to use it in a field check script that does field check directly at input for invalid characters.
therefore i created this script:
function CHKfld (val){
// check the field content
var strPass = val.value;
var strLength = strPass.length;
var txt = "";
for (var i=0; i <= strLength; i++){
var valchar = val.value.charAt(i);
if(valchar.search('[a-z0-9A-Z]') == -1 || valchar == " "){
}
else
{
txt = txt + valchar;
}
}
// place back the content after the change
val.value = txt;
}
and run this on the "onkeyup" event of a <input type="text" HTML box.
up to so far, it works nice, but it doesn't work if you want to navigate back to the left and change something.
therefore i used this script to remember the caret position and place it back afterwards.
but it looks like this script does not work in the "onkeyup" action.
it does select all text from the caret position upto the end of the data.
Did someone had this problem before? and is there a solution?
in Firefox it does work fine.
To test, use the code below, enter some text in the first field, use the arrows to correct something before.
Please note that the positioning still works with the 2nd text field and button...
<html>
<body style="font-family: tahoma; font-size: 8pt;">
<script language="JavaScript">
/*
** Returns the caret (cursor) position of the specified text field.
** Return value range is 0-oField.length.
*/
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
// Return results
return (iCaretPos);
}
/*
** Sets the caret (cursor) position of the specified text field.
** Valid positions are 0-oField.length.
*/
function doSetCaretPosition (oField, iCaretPos) {
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// Create empty selection range
var oSel = document.selection.createRange ();
// Move selection start and end to 0 position
oSel.moveStart ('character', -oField.value.length);
// Move selection start and end to desired position
oSel.moveStart ('character', iCaretPos);
oSel.moveEnd ('character', 0);
oSel.select ();
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0') {
oField.selectionStart = iCaretPos;
oField.selectionEnd = iCaretPos;
oField.focus ();
}
}
function CHKfld (val){
//capture the position of the cursor.
var $carnetpos = doGetCaretPosition(val);
// check the field content
var strPass = val.value;
var strLength = strPass.length;
var txt = "";
for (var i=0; i <= strLength; i++){
var valchar = val.value.charAt(i);
if(valchar.search('[a-z0-9A-Z]') == -1 || valchar == " "){
}
else
{
txt = txt + valchar;
}
}
// place back the content after the change
val.value = txt;
// place the cursor back on it's original position.
doSetCaretPosition (val, $carnetpos);
}
</script>
<form name="blah">
Text Field: <input type="text" name="nameEdit" value="" onkeyup="CHKfld(this)">
<input type="button" value="Get Caret" onClick="alert (doGetCaretPosition (document.blah.nameEdit));">
<hr size=1 noshade>
New Position: <input type="text" name="newPosValue" value="">
<input type="button" value="Set Caret" onClick="doSetCaretPosition (document.blah.nameEdit, parseInt (document.blah.newPosValue.value));">
</form>
</body>
</html>
hendrik.kroon
09-14-2010, 03:55 PM
Dear all,
there I am again.....
It's always a good idea to explain someone else your problem, mostly then you understand your problem better yourself and are you able to solve it yourself!!!
That also happened just now with me again.
The problem above is because there was a caret in the field before the set action was done.
if you remove this caret (by changing the focus) then the script will do exactly what it should do also in this situation.
So i added this line in the set script:
document.forms.blah.newPosValue.focus();
and the problem is solved.
to test:
<html>
<body style="font-family: tahoma; font-size: 8pt;">
<script language="JavaScript">
/*
** Returns the caret (cursor) position of the specified text field.
** Return value range is 0-oField.length.
*/
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
// Return results
return (iCaretPos);
}
/*
** Sets the caret (cursor) position of the specified text field.
** Valid positions are 0-oField.length.
*/
function doSetCaretPosition (oField, iCaretPos) {
// IE Support
if (document.selection) {
// Set focus on the element
document.forms.blah.newPosValue.focus();
oField.focus();
// Create empty selection range
var oSel = document.selection.createRange ();
// Move selection start and end to 0 position
oSel.moveStart ('character', -oField.value.length);
// Move selection start and end to desired position
oSel.moveStart ('character', iCaretPos);
oSel.moveEnd ('character', 0);
oSel.select ();
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0') {
oField.selectionStart = iCaretPos;
oField.selectionEnd = iCaretPos;
oField.focus ();
}
}
function CHKfld (val){
//capture the position of the cursor.
var $carnetpos = doGetCaretPosition(val);
// check the field content
var strPass = val.value;
var strLength = strPass.length;
var txt = "";
for (var i=0; i <= strLength; i++){
var valchar = val.value.charAt(i);
if(valchar.search('[a-z0-9A-Z]') == -1 || valchar == " "){
}
else
{
txt = txt + valchar;
}
}
// place back the content after the change
val.value = txt;
// place the cursor back on it's original position.
doSetCaretPosition (val, $carnetpos);
}
</script>
<form name="blah">
Text Field: <input type="text" name="nameEdit" value="" onkeyup="CHKfld(this)">
<input type="button" value="Get Caret" onClick="alert (doGetCaretPosition (document.blah.nameEdit));">
<hr size=1 noshade>
New Position: <input type="text" name="newPosValue" value="">
<input type="button" value="Set Caret" onClick="doSetCaretPosition (document.blah.nameEdit, parseInt (document.blah.newPosValue.value));">
</form>
</body>
</html>