Suyash Gupta
Suyash Gupta

Reputation: 576

Disable button if textboxes are empty for all the records in a table

I have a table in which I have 2 textboxes & a button and I want to disable the button if any of the textboxes are empty.

I have used the following jquery to do so -

$(document).ready(function () {

    var rdata = $('.chcktbl5').attr("id");

    $('#txtwifiuserid_' + rdata).keyup(function () {
        if ($(this).val().length != 0 && $('#txtwifipass_' + rdata).val().length != 0)
            $('#btnSendSMS').attr('disabled', false);
        else
            $('#btnSendSMS').attr('disabled', true);
    })

    $('#txtwifipass_' + rdata).keyup(function () {
        if ($(this).val().length != 0 && $('#txtwifiuserid_' + rdata).val().length != 0)
            $('#btnSendSMS').attr('disabled', false);
        else
            $('#btnSendSMS').attr('disabled', true);
    })
});

But the problem I am having is that this is only working for the first record of the table, not for all the records.

So, what should I do instead to do this thing for all the records of the table?

Upvotes: 1

Views: 276

Answers (1)

Jonathan Hamel
Jonathan Hamel

Reputation: 1393

You will need to use classes instead of IDs.

$(document).ready(function () {

    $('.textarea').keyup(function () {
      var tableRow = $(this).closest("tr")
      var disable = !!tableRow.find(".textarea").toArray().find((textarea) => { return textarea.value.length === 0});
      tableRow.find('.btnSend').first().attr('disabled', disable);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input type="button" class="btnSend" value="Send" disabled/></td>
    <td><textarea class="textarea"></textarea></td>
    <td><textarea class="textarea"></textarea></td>
   </tr>
   <tr>
    <td><input type="button" class="btnSend" value="Send" disabled/></td>
    <td><textarea class="textarea"></textarea></td>
    <td><textarea class="textarea"></textarea></td>
   </tr>
 </table>

Upvotes: 1

Related Questions