テキスト入力で選択したテキストを削除しようとしているように見えます。2つの異なるアプローチが必要になります。1つはIE<9用で、もう1つはサポートselectionStart
とselectionEnd
プロパティをサポートする他のブラウザー用です。方法は次のとおりです。
デモ: http: //jsfiddle.net/hwG7f/1/
コード:
function deleteSelected(input) {
input.focus();
if (typeof input.selectionStart == "number") {
var start = input.selectionStart,
end = input.selectionEnd,
val = input.value;
if (start != end) {
input.value = val.slice(0, start) + val.slice(end);
input.setSelectionRange(start, start);
}
} else if (typeof document.selection != "undefined") {
document.selection.createRange().text = "";
}
}