Home > Blockchain >  jQuery - disable input field based on another field input value inside table
jQuery - disable input field based on another field input value inside table

Time:01-16

When I input the value in the debit column the credit column will be disabled. Again when I input the value in the credit column the debit column will be disabled. Here's what I'm trying to do to make it happen on every row:

HTML:

<table id="table">
<thead>
    <tr>
        <th>Accounts Ledger</th>
        <th>Debit</th>
        <th>Credit</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>
            <select></select>
        </td>
        <td><input type="number" ></td>
        <td><input type="number" ></td>
    </tr>
</tbody>

jQuery:

    $('input.input-value').focusout(function(){
        var debit = $(this).closest('tr td:nth-child(2) input');
        var credit = $(this).closest('tr td:nth-child(3) input');

        if(parseInt(debit.val()) > 0) {
            credit.attr('disabled','disabled');
        }else{
            debit.attr('disabled','disabled');
        }
        if(parseInt(credit.val()) > 0) {
            debit.attr('disabled','disabled');
        }else{
            credit.attr('disabled','disabled');
        }
    })

Unfortunately, it's not working.

I saw a post on StackOverflow that has a great solution but I can't figure out how it would work for tables. The code is as follows:

 <input id="input1" type="text">
 <input id="input2" type="text">

 let secondInput = $('#input2');
    $("#input1").on(
        "input propertychange",
        event => secondInput.prop(
            'disabled',
            event.currentTarget.value !== "")
  );

Any help would be appreciated.

CodePudding user response:

To do what you require you can hook to the input event of the input and then disable any other input on the same row, using closest(), find(), not() and prop():

$('input.input-value').on('input', e => {
  let $input = $(e.target);
  let $otherInput = $input.closest('tr').find('input').not($input);
  $otherInput.prop('disabled', $input.val().trim().length > 0)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<table id="table">
  <thead>
    <tr>
      <th>Accounts Ledger</th>
      <th>Debit</th>
      <th>Credit</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <select></select>
      </td>
      <td><input type="number" ></td>
      <td><input type="number" ></td>
    </tr>
  </tbody>
</table>

  • Related