Home >Web Front-end >JS Tutorial >How to Get the Cursor Position in a Text Input Field?

How to Get the Cursor Position in a Text Input Field?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 01:14:12670browse

How to Get the Cursor Position in a Text Input Field?

Cursor Position in Input Fields

Query:

How can you determine the cursor position (in characters) within a text input field?

Answer:

Improved Solution:

Use field.selectionStart as mentioned in the provided response.

Original Solution:

For non-jQuery integration, the following code can be utilized:

/*
Returns the caret (cursor) position of the specified text field (oField).
Return value range is 0-oField.value.length.
*/
function doGetCaretPosition(oField) {
  // Initialize
  var iCaretPos = 0;

  // IE Support
  if (document.selection) {
    // Set focus on the element
    oField.focus();

    // To get cursor position, get empty selection range
    var oSel = document.selection.createRange();

    // Move selection start to 0 position
    oSel.moveStart('character', -oField.value.length);

    // The caret position is selection length
    iCaretPos = oSel.text.length;
  }

  // Firefox support
  else if (oField.selectionStart || oField.selectionStart == '0')
    iCaretPos = oField.selectionDirection=='backward' ? oField.selectionStart : oField.selectionEnd;

  // Return results
  return iCaretPos;
}

The above is the detailed content of How to Get the Cursor Position in a Text Input Field?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn