Menu ▼



Posted By :
avatarmrkraju
Total Views : 1692

Auto Resize Textarea (Multi line textbox) while entering data.

This example shows you how to resize the Textarea control while users entering data. When we are working with Textarea control some times the requirement will be the control should auto size according to the data entered by the user. We can achieve this by writing simple JavaScript and Jquery function.

Here is an live example


HTML & JavaScript/JQuery function
<textarea name="txtexample" rows="5" cols="40" id="txtexample" style="overflow: hidden;"></textarea>

For the textarea control we have given rows="5" and cols="40", the rows will be automatically increase /decrease based on the user input.

JavaScript/JQuery function
$(document).ready(function () {
    $("textarea").on("keyup", function () {
        var str = $(this).val();
        var cols = parseInt($(this).attr("cols"), 10);
        var linecount = 0;
        $(str.split("\n")).each(function (ind, val) {
            if (val.length > 0) {
                linecount += Math.ceil(val.length / cols);
            }
            else {
                linecount++;
            }
        })
        linecount++;
        if (linecount > 5)
            $(this).attr("rows", linecount);
        else
            $(this).attr("rows", 5);
    });
});     

In document.ready() event all the textarea controls keyup event will bind, if you want to bind the keyup event for a particular control then change the $("textarea").on("keyup", function () As $("#textareaid").on("keyup", function ()

Source Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script language="javascript">
        $(document).ready(function () {
            $("textarea").on("keyup", function () {
                var str = $(this).val();
                var cols = parseInt($(this).attr("cols"), 10);
                var linecount = 0;
                $(str.split("\n")).each(function (ind, val) {
                    if (val.length > 0) {
                        linecount += Math.ceil(val.length / cols);
                    }
                    else {
                        linecount++;
                    }
                })
                linecount++;
                if (linecount > 5)
                    $(this).attr("rows", linecount);
                else
                    $(this).attr("rows", 5);
            });
        });       
    </script>
</head>
<body>
    <textarea name="txtexample" rows="5" cols="40" id="txtexample" style="overflow: hidden;"></textarea>
</body>
</html>





comments powered by Disqus


Search dotnetlearners.com