jQuery - Effect of transforming text into tag only works on the first row of the table

Asked

Viewed 16 times

2

I’m trying to transform the status of the table into a tag, I got it with jQuery but it’s only applying in the first row of the table (generated with PHP), the rest the text is not replaced.

PHP

<?php foreach ($users as $user): ?>
    <tr>
        <th scope="row"><?=$user->id_matricula?></th>
        <td><?=$user->nm_usuario?></td>
        <td><?=$user->nm_setor?></td>
        <td><?=$user->nm_cargo?></td>
        <td><?=$user->ds_login?></td>
        <td><?=$user->ds_perfil?></td>
        <td><?=$user->dt_create?></td>
        <td><?=$user->dt_update?></td>
        <td class="text-center" id="status"><?=$user->ds_status?></td>
    </tr>
<?php endforeach?>

jQuery

$(function () {
    var op = $("#status").text();
    switch (op) {
        case 'Ativo':
            $("#status").html('<i class="fas fa-circle fa-small-size text-success"></i>');
            break;
        case 'Inativo':
            $("#status").html('<i class="fas fa-circle fa-small-size text-warning"></i>');
            break;
        case 'Bloqueado':
            $("#status").html('<i class="fas fa-circle fa-small-size text-danger"></i>');
            break;
        default:
            break;
    }
});

1 answer

2


In HTML the attribute id must be unique. You can only have 1 per page. You are creating duplicate ids for each row in the table...

Change these id to classes for example and jQuery changes the logic to iterate these lines:

In HTML:

class="text-center status" 

(notes that without the id="...")

In Javascript/jQuery:

$(function() {
  $(".status").each(function() {
    var $el = $(this);
    var op = $el.text();
    switch (op) {
      case 'Ativo':
        $el.html('<i class="fas fa-circle fa-small-size text-success"></i>');
        break;
      case 'Inativo':
        $el.html('<i class="fas fa-circle fa-small-size text-warning"></i>');
        break;
      case 'Bloqueado':
        $el.html('<i class="fas fa-circle fa-small-size text-danger"></i>');
        break;
      default:
        break;
    }
  });
});
  • 1

    Thanks for the guidance, it worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.