setSelectionRange Moves The Field Caret

Move a text field caret or preselect a span with setSelectionRange after programmatic writes, and read selectionStart, selectionEnd, selectionDirection back.

JavascriptForm Validation

Code

javascriptsnippet
17 lines
// Programmatic value writes leave the caret at the start; form code
// uses setSelectionRange to place it deliberately
const field = document.querySelector('#token');
field.value = 'sk_live_9f3ab77c01';

// Caret to the end, where the next keystroke should land
field.focus();
field.setSelectionRange(field.value.length, field.value.length);
console.log('caret at:', field.selectionStart, field.selectionEnd);

// Preselect the prefix so the next input replaces it in one step
field.setSelectionRange(0, 7);
console.log('selected:', field.selectionStart, field.selectionEnd);

// The optional direction decides how Shift+Arrow extends this selection
field.setSelectionRange(3, 8, 'backward');
console.log('direction:', field.selectionDirection);

How it works

The file’s state is a handful of top-level bindings: field.

Watch out for

  • Ready as-is on a bare install of the language.
  • A browser is the runtime here: document are not available in Node.

Using it

Look for the caret at:, selected:, direction: prefixes as the file executes; they connect every printed line to the step behind it.

The key statements that remain

field.setSelectionRange(field.value.length, field.value.length);
const field = document.querySelector('#token');
field.setSelectionRange(3, 8, 'backward');

Interactive Tools for This Topic

FAQ

Does setSelectionRange Moves The Field Caret run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.