I’m trying to create a table with a corresponding textarea
for notes in each row. Additionally, I have a toggle switch that, when enabled, hides all but the first textarea
and makes the first textarea
expand to fill the space of all rows combined.
Here is the HTML and JavaScript code I am using (JS Fiddle):
document.querySelector("input[type=checkbox]").addEventListener("change", e => {
const isChecked = e.target.checked;
const notes = document.querySelectorAll("textarea");
for (let i = 0; i < notes.length; i++) {
const note = notes[i];
const parentCell = note.closest("td");
if (i !== 0) {
parentCell.hidden = isChecked;
} else {
parentCell.rowSpan = isChecked ? notes.length : 1;
}
}
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap demo</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
<table class="table">
<thead>
<tr>
<th>Cat</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td>Luna</td>
<td>
<textarea class="form-control form-control-sm"></textarea>
</td>
</tr>
<tr>
<td>Milo</td>
<td>
<textarea class="form-control form-control-sm"></textarea>
</td>
</tr>
<tr>
<td>Oscar</td>
<td>
<textarea class="form-control form-control-sm"></textarea>
</td>
</tr>
<tr>
<td>Bella</td>
<td>
<textarea class="form-control form-control-sm"></textarea>
</td>
</tr>
</tbody>
</table>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" role="switch">
<label class="form-check-label">Toggle single textarea</label>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
</body>
</html>
When I toggle the checkbox, the first textarea
does not expand to fill the height of all the rows. How can I make the first textarea
stretch to occupy the space of all rows combined when the checkbox is checked?
I’ve tried setting height: 100%
and using various CSS techniques, but none of them worked as expected. I’m looking for a solution that makes the textarea
fully expand vertically within the table cell when other cells are hidden. Any help or guidance would be greatly appreciated!
3
Answers
If you are set on you current implementation you can give the table an id. query select it calculate the box and set the px height of the text area you are working with
E.g.
Only row 0’s textarea?
Or with JS/css
Not too sure if i understood, but here is a naive way to update the first found textarea’s height if isChecked is true: