applying jquery code inside a foreachloop

@foreach($fiche as $f)
<tr id="trTab">
    <td>{{ $f->Date }}</td>
    <td>{{ $f->activite1 }}</td>
    <td>{{ $f->heuresEffectu }}</td>
    <td>{{ $f->Poids }}</td>
    <td>{{ $f->ecart }}</td>

    <form method="post" action="" id="form1">
        <td>
            {{ csrf_field() }}
            <input type="hidden" name="id" value="{{$f->id}}">
            <button type="submit" class="btn btn-primary" id="valider" onclick="">V</button>
        </td>
    </form>
    <form method="post" action="">
        <td>
            <button type="submit" class="btn btn-primary" id="refuser">R</button>
        </td>
    </form>
</tr>
@endforeach

and i have this jquery code which disables a button when i click on it :

<script>
    $("#valider").click(function() {
        if ($('#refuser').prop("disabled")) {
            $('#refuser').attr("disabled", false);
        } else {
            $('#refuser').attr("disabled", true);
        }
        $("#form1").toggle();
    });
</script>

the jquery code is working fine but the problem is whenever i click on one of the buttons it only works for the first row , how do i fix this ?

>Solution :

PHP CODE:

@foreach($fiche as $f)
<tr id="trTab">        
            <td>{{ $f->Date }}</td>
            <td>{{ $f->activite1 }}</td>
            <td>{{ $f->heuresEffectu }}</td>
            <td>{{ $f->Poids }}</td>
            <td>{{ $f->ecart }}</td>
           
            <form method="post" action="" id="form1">
            <td>
            {{ csrf_field() }}
            <input type="hidden" name="id" value="{{$f->id}}">
            <button type="submit" class="btn btn-primary" class="valider" data-id="{{$f->id}}" onclick="">V</button>
            </td></form>
            <form method="post" action="">
            <td>
            <button type="submit" class="btn btn-primary"  id="refuser_{{$f->id}}" data-id="{{$f->id}}">R</button>
            </td>
            </form>
</tr>
@endforeach
  1. Your code won’t work as multiple Same IDs are there and that is the first thumbrule.
  2. If you have multiple elements than try to use class instead of id.
    I have added class="valider" instead of id.
  3. To differenciate which class is clicked you can see I have added data attribute data-id="" will give extra attribute which can help you to retrieve which class id clicked.

Your final jquery code can be like this:

<script>
    $(".valider").click(function() {
        //get current id which was clicked
        var current_id = $(this).data("id");
        if ($('#refuser_'+current_id).prop("disabled")) {
            $('#refuser_'+current_id).attr("disabled", false);
        } else {
            $('#refuser_'+current_id).attr("disabled", true);
        }
        $("#form1").toggle();
    });
</script>

Leave a Reply