0

I need to select a table cell if the previous cell has a checked input. the I have a sneaking suspicion that this is not possible with CSS, can anybody confirm?

Here is an example:

<table>
    <tr>
        <td>Row with checked input</td>
        <td><input type=checkbox checked /></td>
        <td>should show.</td>
    </tr>
    <tr>
        <td>Row with unchecked input</td>
        <td><input type=checkbox /></td>
        <td>should be hidden.</td>
    </tr>
</table>

And the CSS I tried:

td:last-child { display:none; }
input:checked ~ td:last-child { display:initial; }

The first selector works to hide unchecked inputs, but then the second selector cannot make the input show up again. I assume the ~ combinator cannot handle children of previous siblings. Is there any way to get around this using CSS, or do I need to use some JavaScript solution?

JSFiddle for those who want a live scratchpad.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
guhou
  • 1,732
  • 12
  • 32
  • 1
    No way to do this in CSS. http://stackoverflow.com/questions/1817792/css-previous-sibling-selector – Palpatim May 29 '14 at 03:58
  • The `/>` syntax seems really superfluous and strange in the face of unquoted attribute values and `checked` instead of `checked="checked"`. – BoltClock May 29 '14 at 04:50
  • @BoltClock that's true, although the /> close was just added by default by my editor. It doesn't bother me so much that I've edited those out – guhou Jun 15 '14 at 02:24

2 Answers2

1

With the current HTML it is not possible, since CSS cannot look back up to its parent. I.E. The pseudo-selector for the input cannot affect the parent td and following cannot affect the parent's sibling.

If you're flexible with your HTML, you can include the hideable element as a direct sibling inside the same table cell.

<table>
<tr>
    <td>Row with checked input</td>
    <td><input type=checkbox checked /><span>should show.</span></td>
</tr>
<tr>
    <td>Row with unchecked input</td>
    <td><input type=checkbox /><span>should be hidden.</span></td>
</tr>
</table>

CSS

input:not(:checked) + span { display:none; }

I threw this in a JSFiddle http://jsfiddle.net/MghmU/

Ben Patterson
  • 135
  • 1
  • 5
-1

This can't be done with just CSS AND have full browser support yet to the best of my knowledge. So, depending on what browsers you need to support, you will probably need an event listener/handler of some sort to ensure cross-browser compatibility. You will more than likely want to use a javascript solution. If you are familiar with jQuery, that would be the easiest way to handle the task.

jQuery(":checked") --> Check out the api here.

You can then write simple functions for .hide and .show. These can also be found in the api documentation.

The :checked selector is currently only supported by Opera to the best of my knowledge, and according to W3schools.com

Len Paulsen
  • 13
  • 1
  • 6