Mauricio Andrés Mauricio Andrés - 4 months ago 13
Javascript Question

replace text with condition in td jquery

I need to replace text in a td of a table, but with a specific condition, my table is generated dynamically with data of a DB, so there is no limit for the generation of the rows. Currently it only works with one row because of the id but I have tried with the getElementByClassName, but Google Chrome says that the function do not exist.

Here is my table code and my current JS Jquery code:

<table class="table" id="table_headers">
<tr>
<th>Nombre</th>
<th>Correo</th>
<th>Curso inscrito</th>
<th style="text-align:center">Pagado</th>
</tr>

<?php
foreach($stmt->FetchAll() as $results) {
echo "<tr>";
echo '<td>' . $results['name'] . " " . $results['first_last_name'] . '</td>';
echo '<td>' . $results['user_email'] . '</td>';
echo '<td>' . $results['user_course'] . '</td>';
echo '<td id="user_pay">' . $results['user_pay'] . '</td>';
echo "</tr>";
}
?>
</table>

<script>

var pay = document.getElementById("user_pay").innerText;
if (pay == "0" ) {
console.log(pay);
$('#user_pay').html('No');
}else if(pay == "1"){

$('#user_pay').html('Si');
}

</script>

Answer

Here is a jQuery way. We take each element having "user_pay" class. Regarding it's value, we edit its content.

(user_pay shall be a class, as id must be unique. So replace id="user_pay" by class="user_pay" in the PHP part of your code)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" id="table_headers">
                <tr>
                    <th>Nombre</th>
                    <th>Correo</th>
                    <th>Curso inscrito</th>
                    <th style="text-align:center">Pagado</th>
                </tr>
<tr><td>name first_last_name</td><td>user_email</td><td>user_course</td><td class="user_pay">0</td></tr>

<tr><td>name first_last_name</td><td>user_email</td><td>user_course</td><td class="user_pay">1</td></tr>
<tr><td>name first_last_name</td><td>user_email</td><td>user_course</td><td class="user_pay">2</td></tr>
            </table>

    <script>

$(".user_pay").each(function( index ) {
    if ($( this ).text()=="0") {
        $( this ).html("No");
    } else if($( this ).text()=="1") {
        $( this ).html("Si");
    }
});
        
</script>