Jquey - How to take actions with dynamic elements of a table?

Asked

Viewed 30 times

0

I’m making a table that is fed dynamically with database values. In this created table I put a field to insert the "quantity" and a button disabled by a class. I want to enable the button as soon as the user enter a value in the input "quantity", but the way I tried to do with jquery did not work, only works in the elements of the first line (product), in the remaining does not disable the button.

<tbody>
    @foreach ($produtos as $produto)
        <tr>
            <td>{{ $produto->codigo }}</td>
            <td>{{ $produto->produto }}</td>
            <td>{{ $produto->unidade_medida_peso }}</td>
            <td>
                <input type="text" id="inputQuantidade">
            </td>
            <td>
                <a href="#" class="btn disabled" name="addproduto" id="addproduto">
                </a>
            </td>
        </tr>
    @endforeach
</tbody>

And what I tried to do in jquery:

    $( "#inputQuantidade" ).keyup(function() {
    $(this).closest('tr').find('#addproduto').removeClass("disabled");
    });

1 answer

0


The global id attribute defines a unique identifier (ID) that should be unique throughout the document. How you are inside a foreach will happen to exist 2 ID’s and this cannot occur. In your case, you may be making use of classes.

Here’s an example of how you could do the implementation:

<tbody>
    @foreach ($produtos as $produto)
        <tr>
            <td>{{ $produto->codigo }}</td>
            <td>{{ $produto->produto }}</td>
            <td>{{ $produto->unidade_medida_peso }}</td>
            <td>
                <input type="text" class="inputQuantidade">
            </td>
            <td>
                <a href="#" class="btn disabled" name="addproduto" class="addproduto">
                </a>
            </td>
        </tr>
    @endforeach
</tbody>

Another thing is that you need to ensure that the tags are already in the document by the time you run jQuery. Modify your script to follow the instructions below:

$(function() {
    $( ".inputQuantidade" ).keyup(function() {
          $(this).closest('tr').find('.addproduto').removeClass("disabled");
    });
});
  • Perfect! Now it worked. Thank you very much, man!

Browser other questions tagged

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