Am trying to implement the following: Strikethrough a VAT value in a based on a checkbox click in another div.
I tried the following HTML and CSS but it didn't work:
.vat-checkbox:checked .vat-value {
text-decoration: line-through;
}
<table>
<tr>
<td class="vat-check"><input type="checkbox" name="vat-check" class="vat-checkbox"> TVA<small>(19%)</small></td>
<td class="vat-value" id="vat">1 396,500</td>
</tr>
</table>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Can you please advise.
CodePudding user response:
I don't think it is possible with pure CSS with nested elements (table). You can do it if the elements are on the same level:
.vat-checkbox:checked span .vat-value{text-decoration: line-through;}
<input type="checkbox" name="vat-check" class="vat-checkbox">
<span>TVA<small>(19%)</small></span>
<span class="vat-value" id="vat">1 396,500</span>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
For nested elements you can use JavaScript:
const input = document.querySelector('[name="vat-check"]');
const value = document.getElementById('vat');
const handleChange = (e) => {
e.target.checked
? value.classList.add('checked')
: value.classList.remove('checked');
}
input.addEventListener('change', handleChange);
.vat-value.checked {
text-decoration: line-through;
}
<table>
<tr>
<td class="vat-check"><input type="checkbox" name="vat-check" class="vat-checkbox"> TVA<small>(19%)</small></td>
<td class="vat-value" id="vat">1 396,500</td>
</tr>
</table>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Try using javascript, I don't think CSS can achieve what you want if the elements are placed like that.
You were using Adjacent Sibling Selector
div p
example: Select all <p>
tags that immediately follows after <div>
tag
Try the javascript below, using event listener and listen to when the checkbox is clicked then change the style of the vat.
const checkbox = document.querySelector("input[name=vat-check]");
const vat_value = document.getElementById('vat');
checkbox.addEventListener('change', function () {
if (this.checked)
vat_value.style.textDecoration = 'line-through';
else
vat_value.style.textDecoration = 'none';
});
<tr>
<td>
<label for="vat_checkbox">
<input id="vat_checkbox" type="checkbox" name="vat-check" class="vat-checkbox">
TVA<small>(19%)</small>
</label>
</td>
<td><span id="vat">1 396,500</span></td>
</tr>
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>