jquery フォームにフォーカスされた時にテキストを全選択にする
![jquery フォームにフォーカスされた時にテキストを全選択にする](https://mebee.info/wp-content/uploads/2021/07/jquery-36-803x500.gif)
jqueryで、フォームにフォーカスされた時にテキストを全選択にするサンプルコードを記述してます。「focus」と「select」メソッドを使用します。
環境
- OS windows10 pro 64bit
- jquery 3.6.0
- Apache 2.4.43
- ブラウザ chrome 91.0.4472.77
フォームにフォーカスされた時にテキストを全選択
フォームにフォーカスされた時にテキストを全選択するには「focus」と「select」を使用します。
$("要素を指定").focus().click(function () {
$("要素を指定").select();
return false;
});
以下は、テキストフォームにフォーカスすると、テキストが全選択されるサンプルコードを記述してます。
※デザインは「semantic-ui」を使用してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<!-- semantic.css -->
<link rel="stylesheet" type="text/css"
href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
<script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<style>
body>.grid {
height: 100%;
}
.fields {
margin-top: 5px;
}
</style>
<script>
$(function() {
$("#txt").focus().click(function() {
$(this).select();
return false;
});
})
</script>
<body>
<div class="ui middle aligned center aligned grid">
<div class="column">
<form id="frm" class="ui fluid form">
<div class="inline field">
<input id="txt" type="text">
</div>
</form>
</div>
</div>
</body>
</html>
選択されていることが確認できます。
![](https://mebee.info/wp-content/uploads/2021/07/jquery-36.gif)
-
前の記事
Rocky Linux webサーバー「caddy」を構築する 2022.02.27
-
次の記事
javascript エラー「TypeError: “xxx” is not an Object. (evaluating ‘”x” in “xxx”‘)」の解決方法 2022.02.28
コメントを書く