I have an element textarea
, which receives information from a Database. The text can vary, it can be 2, 3, 4...n rows of text, so I would like that when the information obtained in the textarea
, it adjusts automatically and show all the text.
Code:
<table class="table table-sm mb4">
<thead>
<tr>
<th width="22%">Nombre </th>
<th width="22%">Tipo </th>
<th width="23%">Beneficios</th>
<th width="23%">Descripcion de elementos involucrados</th>
</tr>
</thead>
<tbody>
@foreach ($referencia as $item)
<tr>
<td><textarea name="nombre[]" placeholder="... ... ...">{{$item->nombre}}</textarea></td>
<td><textarea name="tipo[]" placeholder="... ... ...">{{$item->tipo}}</textarea></td>
<td><textarea name="beneficio[]" placeholder="... ... ...">{{$item->beneficio}}</textarea></td>
<td><textarea name="descipcion[]" placeholder="... ... ...">{{$item->descipcion}}</textarea></td>
</tr>
@endforeach
</tbody>
This is data that I entered randomly, but the first row actually has more text and as you can see it is only showing a part of it.
Objective:
This is how I would like the text to be displayed, automatically.
We start from the fact that each
textarea
can have a variable length content, therefore a fixed average does not help us, so we can use:scrollHeight
which according to La Mozilla Developer is the total measure of the content in an element considering what is not displayed due to the effect ofoverflow
hiding a part of it.So we do:
textarea
and store them in a variableheight
height
assignee will be delimited byscrollHeight
what will be the total height that the content itself (in this case the text) gives to its parent box or container boxnone
Visually with a result like this:
With this simple code it is solved, every time a line break is made in textarea the style will be registered to the textarea
One way to achieve this is to calculate with
javascript
the sum of the height of thetextarea
and thescroll
and apply this result to the height of the element.For the example, a class has been added
autoheight
to the elementstextarea
where it will be applied. In the example it has been assumed that it is not known which is going to be the tallest element in the row, so they go through all the elements with the classautoheight
and the tallest value is collected to apply it to all and that they have the same height. The different heights are displayed on the console.