「jQuery」selectでフォーカス時に文字を全選択状態にするサンプル
環境
jQuery 3.6.0
Google Chrome 99.0.4844.51
書式
$(セレクタ名).focus().click(function(){
$(this).select();
focus()を利用してフォーカス時に文字を全選択状態にします
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
//テキストボックスにフォーカスが当たった時に実行する
$("input[type='text']").focus()
.click(function(){
$(this).select();
return false;
});
});
</script>
</head>
<body>
<input type="text" value="山田 太郎" name="username">
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
//テキストボックスにフォーカスが当たった時に実行する
$("input[type='text']").focus()
.click(function(){
$(this).select();
return false;
});
});
</script>
</head>
<body>
<input type="text" value="山田 太郎" name="username">
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function(){ //テキストボックスにフォーカスが当たった時に実行する $("input[type='text']").focus() .click(function(){ $(this).select(); return false; }); }); </script> </head> <body> <input type="text" value="山田 太郎" name="username"> </body> </html>
実行結果
テキストボックスにフォーカスを当てると、「山田 太郎」全選択状態となります。