Erlaunis Erlaunis - 6 months ago 23
HTML Question

Loop through the matching table when clicking on a button

I have a dynamically generated html code which looks like :

<div class="systeme">
<table method="post" class="table table_cultures">
<tr class="formRows">
<td>Something</td>
<td>Something</td>
<td>Something</td>
<td>Something</td>
</tr>
</table>
<button class="btn btn-default valider_systeme_culture">Valider</button>
</div>

<div class="systeme">
<table method="post" class="table table_cultures">
<tr class="formRows">
<td>Something 2</td>
<td>Something 2</td>
<td>Something 2</td>
<td>Something 2</td>
</tr>
</table>
<button class="btn btn-default valider_systeme_culture">Valider</button>
</div>


When I click one of the buttons, I want to loop with javascript through the matching table and only this table.

Currently, when I click one button, I get all data of the both tables.

In Javascript, I have this :

var table = $(".table_cultures tbody");
table.find('.formRows').each(function (i) { ... });


I also tried with the function
.parents()
but after that I can't do a
.find('.table_cultures tbody)
, it doesn't work. The thing is that I need to find
table_cultures tbody
because it allows me to loop through the rows when there is a tbody.

How should I do to loop through the right table ?

Answer

You can use $(this).prev('table') where $(this) is clicked button and then you get prev("table") DEMO

$('.btn').click(function() {
  $(this).prev('table').find('.formRows').css('background', 'red')
})