her" /> her" /> her"/>

How to set first position of character in textbox in Textbox click event ---Chrome Issue

3.6k Views Asked by At

See bellow code Here is HTML

 <asp:TextBox ID="txtInTime" runat="server" CssClass="TextBox" Width="60px"
    OnClick="fnFocus(this.id)" ></asp:TextBox>

here is javascript

   function fnFocus(id) {
   document.getElementById(id).focus();    
   }

Above code working in all browser expect chrome... I want textbox click to focus of textbox at first position..In chrome not comming in first position of character.. please help... Any Suggestion...??

2

There are 2 best solutions below

1
palaѕн On

You can do this using setSelectionRange:

function fnFocus(id) {
    var input = document.getElementById(id);
    input.focus();
    input.setSelectionRange(0, 0);
}

Demo: Fiddle

2
seba47 On

setSelecionRange is not working for me in Chrome.

Try this X-Browser:

//Function to set the cursor position and then we set the position for your textbox

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

$('#txtInTime').setCursorPosition(0);

// In your code

<asp:TextBox ID="txtInTime"...... OnClick="$(this).setCursorPosition(0);"></asp:TextBox>

Source