Use JavaScript to place cursor at end of text in text input element

后端 未结 30 3707
时光说笑
时光说笑 2020-11-22 02:48

What is the best way (and I presume simplest way) to place the cursor at the end of the text in a input text element via JavaScript - after focus has been set to the element

30条回答
  •  耶瑟儿~
    2020-11-22 03:47

    While this may be an old question with lots of answers, I ran across a similar issue and none of the answers were quite what I wanted and/or were poorly explained. The issue with selectionStart and selectionEnd properties is that they don't exist for input type number (while the question was asked for text type, I reckon it might help others who might have other input types that they need to focus). So if you don't know whether the input type the function will focus is a type number or not, you cannot use that solution.

    The solution that works cross browser and for all input types is rather simple:

    • get and store the value of input in a variable
    • focus the input
    • set the value of input to the stored value

    That way the cursor is at the end of the input element.
    So all you'd do is something like this (using jquery, provided the element selector that one wishes to focus is accessible via 'data-focus-element' data attribute of the clicked element and the function executes after clicking on '.foo' element):

    $('.foo').click(function() {
        element_selector = $(this).attr('data-focus-element');
        $focus = $(element_selector);
        value = $focus.val();
        $focus.focus();
        $focus.val(value);
    });
    

    Why does this work? Simply, when the .focus() is called, the focus will be added to the beginning of the input element (which is the core problem here), ignoring the fact, that the input element already has a value in it. However, when the value of an input is changed, the cursor is automatically placed at the end of the value inside input element. So if you override the value with the same value that had been previously entered in the input, the value will look untouched, the cursor will, however, move to the end.

提交回复
热议问题