Link to home
Start Free TrialLog in
Avatar of Bryant Farley
Bryant Farley

asked on

Automatic sizing of HTML.TextAreaFor based on content

I have an MVC 5 project with Bootstrap, and a form that relies upon the model for its field content. There are many fields which need to be textareas, to allow up to 255 characters; but I don't want to take up space unnecessarily. Ideally the textarea would begin with a single line, and grow as text is added via data entry (and shrink back as text is deleted).

                <div class="form-group row">
                    <div class="col-md-4">
                        <label>@Html.DisplayNameFor(model => model.FundAgreements)</label>
                    </div>
                    <div class="col-md-8">
                        @Html.TextAreaFor(model => model.FundAgreements, 1, 100, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.FundAgreements)
                    </div>
                </div>

Open in new window


When I had a simple HTML5 form, without Bootstrap, I was able to use the below in $(document).ready for <textarea>, but so far have been unable to modify it successfully to work with Html.TextAreaFor.

 <textarea id="FundAgreements" class="intake-textarea" rows="1" maxlength="255"></textarea>

Open in new window


// Auto resize textarea based on text entered
function resizeTextArea() {
    $(".intake-textarea").keyup(function(e) {
        $(this).height(30);
        $(this).height(this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth")));
    });
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Pawan Kumar
Pawan Kumar
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial