Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  63] [ 6]  / answers: 1 / hits: 15803  / 11 Years ago, thu, august 29, 2013, 12:00:00

I have an HTML table that has a button on every row. The objective here is when a button is clicked, the whole row will got the background color changed.
The code is:



<table>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type=button value=press onclick=myFunction(this) />
</td>
</tr>
<tr>
<td>Value3</td>
<td>Value4</td>
<td>
<input type=button value=press onclick=myFunction(this) />
</td>
</tr>
</table>

<script type=text/javascript>
function myFunction(e) {
//change the background color of the row
}
</script>


Can you help me with this? Thanks!




More From » jquery

 Answers
6

You should use class instead and for good practise remove the inline function calls inside your html.



Use this:



HTML



<table>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type=button value=press />
</td>
</tr>
<tr>
<td>Value3</td>
<td>Value4</td>
<td>
<input type=button value=press />
</td>
</tr>
</table>


jQuery



var all_tr = $('tr');
$('td input[type=button]').on('click', function () {
all_tr.removeClass('selected');
$(this).closest('tr').addClass('selected');
});


Demo here



(updated)


[#76023] Wednesday, August 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
albert

Total Points: 652
Total Questions: 105
Total Answers: 108

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;