wan programmer
wan programmer

Reputation: 71

Jquery not apply for loop call

I have this interface, when I clicked the checkbox, the input will open

interface

I use JQuery for this function and the problem is, only first row is able to open when checked the checkbox. Below are my code:

html:

<div class="row">
      <div class="col">
        <table class="table table-bordered table-hover">
        <tr>
          <th >Name</th>
          <th >Age</th>
        </tr>
        @foreach($peoples as $people)
          <tr>
            <td >
              <input type="checkbox" id="name" name="name" value=""/>&nbsp;&nbsp;
              {{$people->name}}
            </td>
            <td>
              <input type="number" id="age" name="age" value="{{$people->age}}" disabled />
            </td>
          </tr>
        @endforeach

        </table>
      </div>
    </div>

JQuery

<script>
    $(document).ready(function () {
        $('#name').on('change', function () {
            $("#age").prop("disabled", !$(this).is(':checked'));
            $("#age").val('');
        });
    });

    </script>

Upvotes: 0

Views: 39

Answers (1)

Mike B
Mike B

Reputation: 2776

This is because you are creating multiple HTML elements with the same ID. You can change those IDs to classes.

Dynamic approach

You can find the .age input that is in checkbox's parent <tr>:

@foreach($peoples as $people)
<tr>
    <td>
        <input type="checkbox" class="name" value=""/>&nbsp;&nbsp;
        {{$people->name}}
    </td>
    <td>
        <input type="number" class="age" value="{{$people->age}}" disabled />
    </td>
</tr>
@endforeach

And in the Javascript you find the .age input that belongs to the parent

$(document).ready(function () {
    $('.name').on('change', function () {
        let input = $(this).closest('tr').find('input.age')
        input.prop("disabled", !$(this).is(':checked'));
        input.val('');
    });
});

With row identifiers

You could also add an addition attribute to those inputs containing unique values of each one:

@foreach($peoples as $people)
    <tr>
    <td >
        <input type="checkbox" class="name" name="name_{{$people->id}}" person-id="{{$people->id}}"value=""/>&nbsp;&nbsp;
        {{$people->name}}
    </td>
    <td>
        <input type="number" class="age" name="age_{{$people->id}}" person-id="{{$people->id}}" value="{{$people->age}}" disabled />
    </td>
    </tr>
 @endforeach

And then in the Javascript take one according to that attribute of the checkbox:

$(document).ready(function () {
    $('.name').on('change', function () {
        let id = $(this).attr('person-id')
        $('input.age[person-id="'+id+'"]').prop("disabled", !$(this).is(':checked'));
        $('input.age[person-id="'+id+'"]').val('');
    });
});

Upvotes: 1

Related Questions