Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Sunday, May 28, 2017

How To: Set and Get Cursor Position in Textbox using JQuery

In this tutorial, we 'll learn how to set and get cursor position in text box using jquery.
1). Open notepad, and paste following html code in it.

<html>
<head>
 <title>Home</title>
</head>
<body>
 <input id="first_name" type="text" value="webdesignpluscode" />
 <input onclick="SetPosition();" type="button" value="Set Position" />
 <input onclick="GetPosition();" type="button" value="Get Position" />
</body>
</html>

2). Click File then Save As... in notepad menu. Save As dialogue will open
3). Enter "home.html" in File name:
4). Select All Files in Save as type:
5). Click Save. Notepad file will be saved as html page.
6). Now open this html page in edit mode.
7). Add following online JQuery library reference inside <head> tag.

<script src="https://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>

You can download and add to project locally.

8). Now add java script block inside <head> tag and copy following code there.


<script type="text/javascript">

// Set Cursor Position
 $.fn.setCursorPosition = function (position)
{
 this.each(function (index, elem) {
 if (elem.setSelectionRange) {
 elem.setSelectionRange(position, position);
 }
 else if (elem.createTextRange) {
 var range = elem.createTextRange();
 range.collapse(true);
 range.moveEnd('character', position);
 range.moveStart('character', position);
 range.select();
 }
 });
 return this;
 };

 // Get cursor position
 $.fn.getCursorPosition = function ()
{
 var el = $(this).get(0);
 var position = 0;
 if ('selectionStart' in el) {
 position = el.selectionStart;
 }
 else if ('selection' in document) {
 el.focus();
 var Sel = document.selection.createRange();
 var SelLength = document.selection.createRange().text.length;
 Sel.moveStart('character', -el.value.length);
 position = Sel.text.length - SelLength; }
 return position;
 };

 function SetPosition() {
 $("#first_name").setCursorPosition(5);
 $("#first_name").focus();
 }

 function GetPosition() {
 alert($("#first_name").getCursorPosition());
 $("#first_name").focus();
 }
 </script>

Complete code can be downloaded from this git repository.

This is all. You have done. Save file, and view it in any browser.