jQuery selectメソッドでフォームにフォーカスされた時にテキストを全選択にする
環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1
構文
$(指定要素).focus().click(function() {
$(指定要素).select();
return false;
selectとfocusメソッドを使ってフォームにフォーカスされた時にテキストを全選択します。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#username").focus().click(function() {
$(this).select();
return false;
});
});
</script>
</head>
<body>
<input id="username" type="text">
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#username").focus().click(function() {
$(this).select();
return false;
});
});
</script>
</head>
<body>
<input id="username" type="text">
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#username").focus().click(function() { $(this).select(); return false; }); }); </script> </head> <body> <input id="username" type="text"> </body> </html>
実行結果
テキストフォームに「study」と入力し、フォーカスすると、テキストが全選択されます。