Reputation: 596
I have a table with rows that look like this: ( 'o' is a checkbox)
_________________________________________
| o | some label | textarea | o |
|___|______________|___________|_________|
this is it's code:
<table class="table table-condensed table-bordered>
@foreach ($labels as $label)
<tr>
<td class="checkbox"><input type="checkbox" name="checkbox-one />
<td>{{ $label }}</td>
<td class="with-textarea"><textarea></textarea></td>
<td class="checkbox"><input type="checkbox" name="checkbox-two" /></td>
</tr>
@foreach
</table>
How can I achieve that the left checkbox is checked when the user clicks either it or on 'some label' next to it?
I know I need javascript for it, but I don't have much knowledge.
Other similar questions were either really old or didn't help me further.
Upvotes: 1
Views: 1577
Reputation: 856
I think you can done without JS like this:
<table border="">
<tbody>
<tr>
<td><input type="checkbox" id="id-1"></td>
<td><label for="id-1">Click on me</label></td>
<td>Bla bla bla</td>
</tr>
<tr>
<td><input type="checkbox" id="id-2"></td>
<td><label for="id-2">Click on me</label></td>
<td>Bla bla bla</td>
</tr>
<tr>
<td><input type="checkbox" id="id-3"></td>
<td><label for="id-3">Click on me</label></td>
<td>Bla bla bla</td>
</tr>
</tbody>
</table>
Upvotes: 1
Reputation: 1174
The case when you're clicking on the checkbox is done by default. For the label, you want to add a class to the <td>
:
<td class="mylabel">{{ label }}</td>
And then use JS to bind an event handler:
const labels = document.querySelectorAll('.mylabel');
labels.forEach(e => {
e.addEventListener('click', function() {
const cb = e.parentNode.querySelector('.checkbox input');
cb.checked = !cb.checked;
});
});
Upvotes: 3