my page have nested records and each of the nested record has a total number of clicks per each record in a div called "count"
. I want to add 1 to the total number of each div onclick of the button with a class of view
. Currently what i'm achieving is onclick on the button view, 1 is added to the all the nested count divs
, but i want it to affect the particular row on which i click the view button
$(document).ready(function(){
$('.view').click(function() {
counter=parseInt($('.count').html());
counter++;
$('.count').html(counter);
});
});
html
<table width="200" border="1">
<tr>
<td><div>4</div></td>
</tr>
<tr>
<td><button class="view">CLICK ME</button></td>
</tr>
<tr>
<td><div>12</div></td>
</tr>
<tr>
<td><button class="view">CLICK ME</button></td>
</tr>
</table>
Without IDs, you can use parent()
and prev()
to access the previous row in the table, then drill down to your div with find()
.
If there are more than one <div>
in your row, then either
Use find("div").eq(x)
where x is the div index you want starting from 0 (ref).
Give the div a class name like <div class="count_holder">
and you can then do find("div.count_holder")
.
Try this:
$(document).ready(function() {
$('.view').on("click", function() {
$target = $(this).parent().parent().prev().find("div").eq(1);
counter = parseInt($target.html());
counter++;
$target.html(counter);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table width="200" border="1">
<tr>
<td>
<div>Count:</div>
<div>4</div>
</td>
</tr>
<tr>
<td>
<button class="view">CLICK ME</button>
</td>
</tr>
<tr>
<td>
<div>Count:</div>
<div>12</div>
</td>
</tr>
<tr>
<td>
<button class="view">CLICK ME</button>
</td>
</tr>
</table>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments