Reputation:
I have a grid which contains a checkbox. I want to select the row of the grid
for which the checkbox
is checked. Screenshot attached.
Need your help. I am new to Jquery and still learning.
Upvotes: 1
Views: 602
Reputation: 210
You can try this code
$(document).ready(function(){
$(":checkbox").change(function() {
$(this).closest("tr").toggleClass("pinkrow", this.checked)
})
});
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
.pinkrow{
background-color:pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<table>
<tr>
<th>checkbox</th>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td><input type="checkbox" name="tr1" value="tr1" class="checkboxs"> </td>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td><input type="checkbox" name="tr2" value="tr2" class="checkboxs"> </td>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td><input type="checkbox" name="tr3" value="tr3" class="checkboxs"> </td>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td><input type="checkbox" name="tr4" value="tr4" class="checkboxs"> </td>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
</table>
</body>
</html>
Upvotes: 1
Reputation: 56650
You could write it with closest()
method like so!
We get the input that is checked with input:checked
then we find the tr
parent using the closest method.
$('#check').on("click", function() {
var checked = $('#asdf input:checked');
console.log(checked.closest('tr'));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="asdf">
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>$100</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>$1050</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>$1002</td>
</tr>
</table>
<button id="check">check</button>
Upvotes: 1
Reputation: 4870
I dont know if you are using a library for that datatable.
But with jQuery you could do something like this.
The jQuery code below should also work with your html structure.
$(".dataTable > tbody").find("tr td:first-child input[type='checkbox']:checked").each(function (){
$(this).parent().parent().addClass("selected")
});
.selected >td{
background:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="dataTable">
<tr>
<td>
<input type="checkbox" checked="checked" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" checked="checked" />
</td>
</tr>
</table>
Upvotes: 0