csshtml-tabletextareaheight

Make table row height adjust to textarea content


I have the following table with a textarea inside the td:

#myarea {
    box-sizing: border-box;
    border: none;
    width: 100%;
    height: 100%;
    resize: none;
}
<table>
    <thead>
    <tr>
        <th>n1</th>
        <th>n2</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>HalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHallo</td>
        <td>
            <textarea id="myarea"></textarea>
        </td>
    </tr>
    </tbody>
</table>

The result looks like this:

enter image description here

How can I set the whole table row height dynamically to be as high as the textarea content?

Thank you!


Solution

  • To set the table row height dynamically based on the content of a textarea, you can use JavaScript to adjust the height of the textarea as the content changes.

    function autoResize(textarea) {
    textarea.style.height = 'auto'; // Reset the height
    textarea.style.height = textarea.scrollHeight + 'px'; // Set the height to scroll height
    }
    #myarea {
    box-sizing: border-box;
    border: none;
    width: 100%;
    resize: none;
    overflow: hidden;
    }
    <table>
    <thead>
    <tr>
    <th>n1</th>
    <th>n2</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td>HalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHallo</td>
    <td>
    <textarea id="myarea" oninput="autoResize(this)"></textarea>
    </td>
    </tr>
    </tbody>
    </table>

    The autoResize function is called whenever the input event is triggered on the textarea. The textarea height is first reset to auto to shrink back down if the content has been reduced. Then, the textarea height is set to its scrollHeight, which is the height of the content of the textarea.