www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 17

Thread: How to set/get caret position of a textfield in IE?

  1. #1
    Join Date
    Jun 2005
    Posts
    8

    How to set/get caret position of a textfield in IE?

    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!

  2. #2
    Join Date
    Jul 2005
    Location
    India
    Posts
    145

    to set caret position

    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>
    Last edited by deep.dhyani; 08-05-2005 at 02:03 AM. Reason: There is some errors.

  3. #3
    Join Date
    Aug 2005
    Posts
    1

    Get/Set Caret Code for IE and Mozilla

    I have searched all over for code like this, but found nothing suitable, so I rolled my own:

    HTML Code:
    <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
    Last edited by m2pc; 08-24-2005 at 01:49 PM. Reason: Mistake

  4. #4
    Join Date
    Jul 2006
    Posts
    1

    Getting/Setting the Selected Text (Caret Positions) within a Text Box in IE and FF.

    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!

  5. #5
    Join Date
    Aug 2006
    Posts
    4
    Is there any other similar way to set the cursor position back in contenteditable div??

  6. #6
    Join Date
    Aug 2007
    Posts
    2

    Smile

    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>

  7. #7
    Join Date
    Dec 2008
    Posts
    1

    Star Selection

    hi pp... Ive found this doGetCaretPosition() function in many foruns and tip sites and Ive 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.

    Code:
    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);
    
    }

  8. #8
    Join Date
    Nov 2009
    Posts
    7

    Cool Cross-browser Set Caret function for any element in the dom tree

    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...

    Code:
            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"

  9. #9
    Join Date
    Dec 2009
    Posts
    13
    Quote Originally Posted by m2pc View Post
    I have searched all over for code like this, but found nothing suitable, so I rolled my own:

    HTML Code:
    <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?

  10. #10
    Join Date
    Dec 2009
    Posts
    13
    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.

  11. #11
    Join Date
    Oct 2006
    Posts
    939
    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...
    HTML Code:
    <!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>

  12. #12
    Join Date
    Dec 2009
    Posts
    13
    Quote Originally Posted by justinbarneskin View Post
    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 Code:
    <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));">

  13. #13
    Join Date
    Oct 2006
    Posts
    939
    HTML Code:
    <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>

  14. #14
    Join Date
    Dec 2009
    Posts
    13
    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.

  15. #15
    Join Date
    Aug 2010
    Posts
    3
    <!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>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles