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?

Creating an Automatically Resizing Textarea for User Input

Posted at

What We Want to Achieve

We want the text area where users input text, such as in a search box, to automatically resize itself when the amount of text exceeds the initial size.

image.png

image.png

Code

※ Feel free to change the versions of Bootstrap and jQuery to your preference.

<!DOCTYPE html>
<html lang="en">
<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'; // Set to scroll height
    }
    textarea.addEventListener('input', autoResize); // Adjust size on input
    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="Search criteria" 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>

Comment: It would be great if this becomes standard in 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?