9

My HTML: <tr><td>Text</td><td><input type="text" value=""></td></tr>

My CSS: input:focus tr{ background-color:#fff;}

I want to highlight the row in white when I'm writing text in the input field. I know "tr" is before "input", but is this possible to do in any way?

Thanks a bunch

Joel
  • 895
  • 4
  • 13
  • 33

5 Answers5

9

No, sadly. See: Complex CSS selector for parent of active child

Here's how you could do it, though: http://jsfiddle.net/minitech/udzcp/

Community
  • 1
  • 1
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Thank you very much for this link! You just saved me alot of time – Joel May 13 '11 at 02:17
  • Oh, and by the way, I edited my post to include an example of how you might do it with JavaScript. – Ry- May 13 '11 at 02:19
5

Using JQuery, it is very possible. Observe:

HTML

<table border="1" cellpadding="20">
    <tr>
        <td>Text</td>
        <td height="50" width="100" id="somename"><input type="text" value="" id="mirza"></td>
    </tr>
    <tr><td>&nbsp;</td><td>&nbsp;</td></tr>
    <tr><td>a&nbsp;</td><td>1&nbsp;</td></tr>
    <tr><td>a&nbsp;</td><td>1&nbsp;</td></tr>
    <tr><td>a&nbsp;</td><td>1&nbsp;</td></tr>
    <tr><td>a&nbsp;</td><td>1&nbsp;</td></tr>
    <tr><td>a&nbsp;</td><td>1&nbsp;</td></tr>
</table>

CSS

.highlightedRow { background-color: orange; }

Jquery

$('input').focus(function() {
    $(this).parent().parent().addClass('highlightedRow');
});

$('input').blur(function() {
    $(this).parent().parent().removeClass('highlightedRow');
});
1

Sadly, there's no way to style the parent element with CSS, so you'll have to use javascript.

Emmett
  • 14,035
  • 12
  • 56
  • 81
1

This is good for when you are generating a lot of similar rows (looping through large datasets, etc): Script:

function rowSet(data_id){
    document.getElementById('row_' + data_id).style.backgroundColor = 'blue';
}
function rowReset(data_id){
    document.getElementById('row_' + data_id).style.backgroundColor = '';
}

Body:

<body>
    <form>
        <table>
            <tr id="row_#data_id#">
                <td><input name="input1_#data_id#" onFocus="rowSet(#data_id#);" onBlur="rowReset(#data_id#);"></td>
                <td><input name="input2_#data_id#" onFocus="rowSet(#data_id#);" onBlur="rowReset(#data_id#);"></td>
            </tr>
        </table>
    </form>
</body>

You could also use currentRow, or whatever you prefer.

kodemonki
  • 11
  • 1
-1

This jquery code should do it:

$('input').focus(function() {
    $('tr').css("background-color", "#c00");
});

Demo here

raeq
  • 971
  • 4
  • 15
  • 36
  • See: http://jsfiddle.net/9mR95/ That code will highlight all rows and not just the parent of the input element when one is selected and won't un-higlight the row after blur. – Ry- May 16 '11 at 18:05