40

when you click on 'Ask question' here in Stackoverflow you see a text "What's your programming question? Be descriptive."

i want the same thing and all i need for that is to move my cursor to the beginning of the text field. how do i do that with jquery?

ajsie
  • 77,632
  • 106
  • 276
  • 381

4 Answers4

30

May be that is an overkill, but these functions are helpful to select a portion of an input field.

The code below place the cursor to the first char of the second field.

<html>
<head>
    <title>so</title>
</head>
<body>
    <input value="stack" />
    <input value="overflow" />
    <script>
        var inp = document.getElementsByTagName('INPUT')[1];
        if (inp.createTextRange) {
            var part = inp.createTextRange();
            part.move("character", 0);
            part.select();
        } else if (inp.setSelectionRange) {
            inp.setSelectionRange(0, 0);
        }
        inp.focus();
    </script>
</body>
</html>
Chango
  • 6,754
  • 1
  • 28
  • 37
Mic
  • 24,812
  • 9
  • 57
  • 70
  • It's worth noting that the `createTextRange` piece of this answer can be omitted if you aren't supporting Internet Explorer. – 96ethanh Aug 12 '21 at 18:27
18

You can use focus() method. If I recall jQuery, its like this: $("#question_input_field_id").focus(); (If I got your question right)

Update: Setting cursor at the beginning:

$("#question_input_field_id").focus();
$("#question_input_field_id").get(0).setSelectionRange(0,0);
Tony Brix
  • 4,085
  • 7
  • 41
  • 53
Sejanus
  • 3,253
  • 8
  • 39
  • 52
6

if you look into the source code of stackoverflow > ask question, you will find this:

<table style="width:668px"> 
     <tr> 
         <td style="width:50px"><label for="title">Title</label></td> 
         <td style="padding-left:5px"><input id="title" name="title" type="text" maxlength="300" tabindex="100" style="width:610px" value=""> 
              <span class="edit-field-overlay">What's your programming question? Be descriptive.</span> 
         </td> 
     </tr> 
</table>

what really is happening is that a CSS code made the <span class="edit-field-overlay"> move over the top of input box and show hide when needed... and just do what Sejanus' suggested.

Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
-1
 $('#txtYourTextBox').blur(function () { 
    var val = $("#txtYourTextBox").val();
    $("#txtYourTextBox").val('');
    setTimeout(function () { $("#txtYourTextBox").val(val); }, 20);
});
Yoky
  • 832
  • 10
  • 20
  • Looks like this code caches the value of the input, clears it, then reapplies the same value. All of this happening every time focus leaves the input. I'm not sure how this is supposed to answer the question. – Michael Martin-Smucker May 23 '14 at 16:00