How to Select particular text in textbox while textbox receives focus

北城以北 提交于 2019-12-02 02:44:30

assume you have TextInput you want to select its first character, whenever its selected

<input id="MyText" type="text" value="text" onclick="MyText_click()" />

and the script is like this:

<script>

    function MyText_click() {

        var input = document.getElementById("MyText");
        createSelection(input, 0, 1); // first character
    };

    function createSelection(field, start, end) {
        if (field.createTextRange) {
            var selRange = field.createTextRange();
            selRange.collapse(true);
            selRange.moveStart('character', start);
            selRange.moveEnd('character', end);
            selRange.select();
            field.focus();
        } else if (field.setSelectionRange) {
            field.focus();
            field.setSelectionRange(start, end);
        } else if (typeof field.selectionStart != 'undefined') {
            field.selectionStart = start;
            field.selectionEnd = end;
            field.focus();
        }
    }

</script>
Amir Sherafatian

you can do that programmatically using javascript, see this: Programmatically selecting partial text in an input field

Create event for text focus

Now we have two properties

   txt.SelectionStart = intValue

and

  txt.selectionLength = length;

Use this property to resolve your stuff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!