0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Bootstrap でテキストボックスのサイズが大きくなったときに自動でリサイズしたい(令和7年版)

Last updated at Posted at 2025-01-18

やりたいこと

検索などのテキストボックス(正確にはテキストエリア)に入力された文字列が長くなったときに、自動でサイズを変更したい

image.png

image.png

コード

※ bootstrap, jQuery のバージョンはお好みのものに変更してください。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello Resizable Textarea</title>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">

<!-- jQuery 3.5.1 -->
<script src="https://code.jquery.com/jquery-3.5.1.js"
	integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
	crossorigin="anonymous"></script>

<!-- bootstrap 5 -->
<link
	href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
	rel="stylesheet"
	integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
	crossorigin="anonymous">

<!-- Bootstrap Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">

<script type="text/javascript" class="init">
$(document).ready(function() {
    const textarea = document.querySelector('.input-group textarea');
    function autoResize() {
    	textarea.style.height = 'auto';
    	textarea.style.height = this.scrollHeight + 'px'; // スクロール高さに設定
    }
    textarea.addEventListener('input', autoResize); // 入力ごとにサイズ調整
    autoResize();
});
</script>

</head>

<body class="m-3">
    <div class="container mt-5">
        <div class="row">
            <div class="col">
                <div class="input-group mb-3">
                    <textarea class="form-control" placeholder="検索条件" aria-label="Search" rows="1" ></textarea>
                    <button id="btn_search" type="submit" class="btn btn-primary"><i class="bi bi-search"></i></button>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

コメント:HTMLの標準規格になってくれるとうれしい


以上.

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?