Get cursor position (in characters) within a text Input field

后端 未结 9 1354
孤城傲影
孤城傲影 2020-11-22 01:22

How can I get the caret position from within an input field?

I have found a few bits and pieces via Google, but nothing bullet proof.

Basically something lik

9条回答
  •  日久生厌
    2020-11-22 01:41

    There are a few good answers posted here, but I think you can simplify your code and skip the check for inputElement.selectionStart support: it is not supported only on IE8 and earlier (see documentation) which represents less than 1% of the current browser usage.

    var input = document.getElementById('myinput'); // or $('#myinput')[0]
    var caretPos = input.selectionStart;
    
    // and if you want to know if there is a selection or not inside your input:
    
    if (input.selectionStart != input.selectionEnd)
    {
        var selectionValue =
        input.value.substring(input.selectionStart, input.selectionEnd);
    }
    

提交回复
热议问题