Heru Nugroho Heru Nugroho - 7 months ago 16
Javascript Question

jquery disable each button

i have a table with text area and button
and i want button disabled when text area is empty and enabled when not empty or user fill that text area

this is my sample html code
i use php looping for generate this table

<table>
<tr>
<td><textarea name="text1" id="text1"></textarea></td>
<td><input type="button" class="btn btn-primary" id="btn1"></td>
</tr>
<tr>
<td><textarea name="text2" id="text2"></textarea></td>
<td><input type="button" class="btn btn-primary" id="btn2"></td>
</tr>
<tr>
<td><textarea name="text3" id="text3"></textarea></td>
<td><input type="button" class="btn btn-primary" id="btn3"></td>
</tr>
</table>


for disabling button i wanna use addclass "disabled" and romoveclass "enabeled"
and for enabeling use addclass "enabeled" and removeclass "disabled"

please help me with jquery.
thx before

Answer

You can do something like this:

$('textarea').on('keyup keydown keypress change paste', function() {
    if ($(this).val() === '') {
      $(this).closest('tr').find('.btn').removeClass('enabled').addClass('disabled')
    } else {
      $(this).closest('tr').find('.btn').removeClass('disabled').addClass('enabled')
    }
  });
.disabled {
  color: red;
  }

.enabled {
  color: green;
  }
You can do something like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
<tr>
<td><textarea name="text1" id="text1"></textarea></td>
<td><input type="button" class="btn btn-primary disabled" id="btn1" value="Submit"></td>
</tr>
<tr>
<td><textarea name="text2" id="text2"></textarea></td>
<td><input type="button" class="btn btn-primary disabled" id="btn2" value="Submit"></td>
</tr>
<tr>
<td><textarea name="text3" id="text3"></textarea></td>
<td><input type="button" class="btn btn-primary disabled" id="btn3" value="Submit"></td>
</tr>
</table>