user3041439 user3041439 - 4 months ago 27
jQuery Question

Traversing through rows of a webgrid and performing jQuery magic MVC4

I have the following HTML being rendered.

<tr class="webgrid-row-style">
<td class="webgrid-column-style">
<span class="activate"><label id="lblMTPrinterID1">MT1</label></span>
<span class="deactivate"><label id="lblMTPrinterID2">MT1</label></span>
</td>
<td class="webgrid-column-style">
<span class="activate"><label id="lblNTPrinterID1">NT1</label></span>
<span class="deactivate"><label id="lblNTPrinterID2">NT1</label></span>
</td>
<td class="webgrid-active-column-style">
<span class="activate selector"><label id="lblActive1">N</label></span>
<span class="deactivate selector"><label id="lblActive2">N</label></span>
</td>
<td class="webgrid-column-style">
<button class="activate edit-user">Activate</button>
<button class="deactivate edit-user">Deactivate</button>
</td>
</tr>
<tr class="webgrid-alternating-row">
<td class="webgrid-column-style">
<span class="activate"><label id="lblMTPrinterID1">MT2</label></span>
<span class="deactivate"><label id="lblMTPrinterID2">MT2</label></span>
</td>
<td class="webgrid-column-style">
<span class="activate"><label id="lblNTPrinterID1">NT2</label></span>
<span class="deactivate"><label id="lblNTPrinterID2">NT2</label></span>
</td>
<td class="webgrid-active-column-style">
<span class="activate selector"><label id="lblActive1">Y</label></span>
<span class="deactivate selector"><label id="lblActive2">Y</label></span>
</td>
<td class="webgrid-column-style">
<button class="activate edit-user">Activate</button>
<button class="deactivate edit-user">Deactivate</button>
</td>
</tr>


I wish to use jQuery to traverse through each row, find its text of label lblActive1 and hide the row's activate elements if lblActive1 is Y. If lblActive1 is N, I will hide the row's deactivate elements. I have the following jQuery script which is hiding either the activate or deactivate elements across the entire table which is not my intention. I only wish to hide them on a row by row basis depending on the row's lblActive text.

$('tr.webgrid-row-style').each(function () {
var Active = $("#lblActive1").text();
if (Active == "Y") {
$('.activate').hide();
}
else {
$('.deactivate').hide();
}

});


Hi do I do this please? Many thanks.

Answer

Try with - The jQuery "find" method looks for descendant of the current selection (even if the ID is not unique in the whole DOM)

    $(document).ready(function () {
        $('tr.webgrid-row-style, tr.webgrid-alternating-row').each(function () {
            var Active = $(this).find("#lblActive1").text();
            if (Active == "Y") {
                $(this).find('.activate').hide();
            }
            else {
                $(this).find('.deactivate').hide();
            }
        });
    });