18
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

「テキストボックスのフォーカス時に選択状態にする」を少しだけクロスブラウザ対応した

Last updated at Posted at 2014-09-03

以下のコードでinputタグをフォーカス時に選択状態になるようにしたら、
SafariとかAndroidブラウザとかで動かなかった。

HTML
<input id="test"></input>
JS
var input = document.getElementId("test");
input.onfocus = focusInput;

function focusInput(e) {
	if (e) {
		var target = e.target;
		target.select();
	}
}

というわけで以下のコードに変更

JS
var input = document.getElementId("test");
input.onfocus = focusInput;

function focusInput(e) {
	if (e) {
		(function(e){
        setTimeout( function() {setFocus(e);});
	})(e);
	}
}

function setFocus(e) {
	if (e) {
		var targetTag = e.target;
		targetTag.focus();
		//とりあえず全選択、選択範囲指定したいときはbgnとendを適宜指定
		var num = targetTag.value.length;
		var bgn = 0;
		var end = num;
		if(typeof(targetTag.selectionStart) != "undefined"){
			targetTag.selectionStart = bgn;
			targetTag.selectionEnd = end;
		} else if(document.selection) {
			var range = targetTag.createTextRange();
			range.collapse();
			range.moveEnd( "character", bgn );
			range.moveStart( "character", end );
			range.select();
		}	
	}
}

FireFox,Chrome,Safari,IE9,IE11,Android標準ブラウザ,Mobile Safari(iOS7)ではとりあえず動きました。

18
17
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?