Ali Hamra Ali Hamra - 7 months ago 16
Javascript Question

Change color of table row when an input within is focused

Suppose I have a table like this with

<tr>
and
<td>
inside PHP loop :

//Some code...
echo "<table id='rowClick'>";
while($row=mysql_fetch_assoc($result){

echo "<tr><td><input type='text' value='{$row['item']}'></td></tr>";
}
echo "</table>";
//Rest of code


I've used a CSS :

table tr.active{
background:red;
}


And For JQuery :

<script>

$(document).ready(function(){
$("#rowClick").children("tbody").children("tr").children("td").keydown(function(){
$(this.parentNode).toggleClass("active");
});
$("#rowClick").children("tbody").children("tr").children("td").keyup(function(){
$(this.parentNode).toggleClass("active");
});
});
</script>


I'm not so familiar with JQuery. All I want is that when user select
<td>
input field ( or being focused ) in any row, the color of the
<tr>
will be changed . According to the above jquery it works but not as expected, because each time I select input field it turns red, then when selecting next one it returns back to default table color and so on.

Answer

I think this is what you are looking for:

$(document).ready(function(){
    $("#rowClick").find("input").on("focus", function(){
      $(this).closest("tr").addClass("active");
    }).on("blur", function() {
      $(this).closest("tr").removeClass("active");
    })
});

I'm targeting the input from the table to look for focus/blur, then from the inputs I'm targeting the closest parent tr to highlight.

JSFiddle

If you want to highlight the td instead, just target that instead:

JSFiddle