How to make only involved row's button enable?

Viewed 33

I have a table and the body is using foreach loop.

 <?php foreach ($list as $test) : ?>

                    <tr>

                        <td>
                            <?= form_open_multipart('/test/update/' . $test['id'], ['class' => 'needs-validation', 'novalidate' => '']); ?>
                            <?= form_dropdown(
                                'something',
                                $option,
                                $test['smt'],
                                ['required' => '', 'id' => 'smt2', 'class' => 'd-block col-12 form-control']
                            ); ?>
                        </td>

                        <td align="right"><button class="btn btn-success btn-sm" type="submit" id="submit" disabled>SAVE UPDATE</a></td>

                        <?= form_close(); ?>
                       </tr>
                <?php endforeach; ?>

For the javascript I do :

 $(document).ready(function() {
   

    $('select').on('change', function() {
           $('button').attr('disabled', false);
       });
    });

When user change the value of the drop down, then the 'Save Update' button will be enabled. For now, all the button will be enabled if user change on any drop down no matter in which row. I wish to enabled only Save button in which row the drop down was changed.

1 Answers

You need to use DOM traversal to find the button related to the select which raised the change event. You can get a reference to the button using the event that's passed to the handler function. From there you can get the nearest common tr using closest() and then find(). Try this:

jQuery($ => {
  $('select').on('change', e => {
    $(e.target).closest('tr').find('button').prop('disabled', false);
  });
});

Note the use of prop() to set the disabled flag instead of attr(). Use of prop() is preferred where possible, as it avoid unnecessary accesses of the DOM which increases performance.

Related