开发者

move cursor to the beginning of the input field?

开发者 https://www.devze.com 2022-12-17 18:48 出处:网络
when you click on \'Ask que开发者_开发知识库stion\' here in Stackoverflow you see a text \"What\'s your programming question? Be descriptive.\"

when you click on 'Ask que开发者_开发知识库stion' 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?


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>


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);


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.


 $('#txtYourTextBox').blur(function () { 
    var val = $("#txtYourTextBox").val();
    $("#txtYourTextBox").val('');
    setTimeout(function () { $("#txtYourTextBox").val(val); }, 20);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消