move cursor to the beginning of the input field?

前端 未结 4 881
面向向阳花
面向向阳花 2020-12-01 11:39

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 f

相关标签:
4条回答
  • 2020-12-01 12:25
     $('#txtYourTextBox').blur(function () { 
        var val = $("#txtYourTextBox").val();
        $("#txtYourTextBox").val('');
        setTimeout(function () { $("#txtYourTextBox").val(val); }, 20);
    });
    
    0 讨论(0)
  • 2020-12-01 12:34

    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.

    0 讨论(0)
  • 2020-12-01 12:35

    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>
    
    0 讨论(0)
  • 2020-12-01 12:39

    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);
    
    0 讨论(0)
提交回复
热议问题