HTMLInputElement.setSelectionRange()
関数は<input>
または、<textarea>
要素に対して有効です。要素に対して任意の開始と末尾のポジションを設定することでテキストを選択状態にします。
更に、より新しいブラウザでは選択する方向をも考慮する必要があります。つまり、ユーザーがクリックした後ドラッグして選択状態にする際のドラッグの方向が、はじめからなのか、おしりからなのか、考慮するということです。
この関数はアップデートされ、HTMLInputElement.selectionStart
, selectionEnd
, and selectionDirection
プロパティを一度に呼び出し更新することができます。
Note that accordingly to the WHATWG forms spec selectionStart
, selectionEnd
properties and setSelectionRange
method apply only to inputs of types text, search, URL, tel and password. Chrome, starting from version 33, throws an exception while accessing those properties and method on the rest of input types. For example, on input of type number: "Failed to read the 'selectionStart' property from 'HTMLInputElement': The input element's type ('number') does not support selection.".
Syntax
element.setSelectionRange(selectionStart, selectionEnd [, selectionDirection]);
Parameters
selectionEnd
がselectionStart
より小さい場合、両方の値はselectionEnd
として扱われます。
selectionStart
- 0を基準とした選択状態の文字のインデックス。指定されたインデックスが文字の長さより長い場合は、文字の長さをインデックスに指定したものとみなされます。
selectionEnd
- 0を基準とした選択状態の最後の文字のインデックス。指定されたインデックスが文字の長さより長い場合は、文字の長さをインデックスに指定したものとみなされます。
selectionDirection
Optional- 選択する際の方向を指定します。取りうる値は以下のとおりです。
"forward"
"backward"
"none"
選択する際の方向が指定されていない時です。デフォルト値になります。
Example
サンプルの中のボタンをクリックすると、テキストボックスの3,4,5番目の文字が選択状態になります。 ("Mozilla"の"zil").
HTML
<input type="text" id="text-box" size="20" value="Mozilla">
<button onclick="selectText()">Select text</button>
JavaScript
function selectText() {
const input = document.getElementById('text-box');
input.focus();
input.setSelectionRange(2, 5);
}
実行結果
仕様
Specification | Status | Comment |
---|---|---|
HTML Living Standard HTMLInputElement.setSelectionRange() の定義 |
現行の標準 | No change |
HTML 5.1 HTMLInputElement.setSelectionRange() の定義 |
勧告 | No change |
HTML5 HTMLInputElement.setSelectionRange() の定義 |
勧告 | Initial definition |
ブラウザ互換性
BCD tables only load in the browser