1

So, I have a project in laravel and now i'm working on the CRUD, specifically in the Update. Here I've a btn modal that show me the dates for edit and there I´ve a select dynamic.

The table with the btn:

@foreach ($mascotas as $mascota)
  <tr>
     <td class="text-center">{{$mascota->name}}</td>
     <td class="text-center"> {{$mascota->especie}}</td>
     <td class="text-center">{{$mascota->raza}}</td>
     <td> <button class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#modalEditCli" 
      onclick="modalEdit('{{$mascota->id}}', '{{$mascota->name}}', '{{$mascota->especie}}', 
      '{{$mascota->razaId}}', '{{$mascota->raza}}')"> <i class="fa fa-edit"></i> </button>
     </td>
  </tr>
@endforeach
@include('mascotas.modal_editar')

So, in the btn I'm calling the modal and the JS function at the same time.

The modal:

<div class="modal fade" id="modalEditCli" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form action="{{route('mascotas.store')}}" method="get" class="formularin"> @csrf
                    <div class="row">
                        <div class="col-4">
                            <div class="mb-3">
                                <label for="name" class="form-label"><b>Nombre Mascota:</b> <span class="text-secondary">*</span></label>
                                <input class="form-control" type="text" name="mascota_nm" id="mascota_nm" value="" required>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="mb-3">
                                <label for="especie" class="form-label"><b>Especie:</b> <span class="text-secondary">*</span></label>
                                <select class="form-control especie" name="especie" id="especie" required>
                                    <option name="especie" value="0">Otro...</option>
                                    <option name="especie" value="1">Perro</option>
                                    <option name="especie" value="2">Gato</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="mb-3">
                                <label for="raza" class="form-label"><b>Raza:</b> <span class="text-secondary">*</span></label>
                                <select class="form-control raza" name="raza" id="raza" required>
                                    <option value="0">Otro...</option>
                                </select>
                            </div>
                        </div>
                    </div>
            <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
                    <button type="button" class="btn btn-warning"> <i class="fa fa-edit"></i> Editar</button>
                </form>
            </div>
        </div>
    </div>
</div>

And here my JS function for the Select:

<script>
    function modalEdit(id, name, especie, razaId, raza){
            $('#id').val(id);
            $('#mascota_nm').val(name);
            $('.especie').val(especie);
            $(".raza").prop('disabled', true); // Aplica el atributo "disabled" en el select.
            $(".raza").html("<option value='"+ razaId +"'>"+ raza +"</option>"); // Limpia los datos del Select y solo deja la raza.
            $(".especie").change(function(){
                $(".raza").html("<option value='0'>Otro...</option>"); // Limpia los datos del Select y solo deja la opcion "Otro..."
                var selectEspe = $('.especie').val();
                $.post({
                    url: '/mascotas/dinamicQuery',
                    method: 'POST',
                    data: {
                        selectEspe,
                        _token: $('input[name="_token"]').val()
                    }
                }).done(function(res){
                    $(".raza").prop('disabled', false); // Elimina el atributo "disabled"
                    var razas = JSON.parse(res);        // Lee el archivo Json
                    $.each(razas, function(key, value){
                        var consulta = $(".raza").append('<option name="' + value.id + '">' + value.raza + '</option>');
                    });
                });
            });
        }
    </script>

And for last the Laravel query:

public function dinamicQuery(Request $request){
   $especie = $request->selectEspe;
   $razas = Especie::all()->where('especie', '=', $especie);
   return response(json_encode($razas))->header('Content-type', 'text/plain');
}

So, the js query and the rest is working, if I open my modal it once the js query runs perfectly. But the problem is when I open any modal edit of the table for a second time o more. The "each" of my js query it runs as many times as modal is opened and I don´t know how why or how I can stop it.

Thanks for everything!

1 Answers1

0

The problem is that every time when you click the edit <button/> it calls the modalEdit() function that attaches a new $(".especie").change() event.

Perhaps, the best solution is to move $(".especie").change() outside of the modalEdit() function. A quick workaround would be the .one()

Example:

<script>
    function modalEdit(id, name, especie, razaId, raza){
        $('#id').val(id);
        $('#mascota_nm').val(name);
        $('.especie').val(especie);
        $(".raza").prop('disabled', true); // Aplica el atributo "disabled" en el select.
        $(".raza").html("<option value='"+ razaId +"'>"+ raza +"</option>"); // Limpia los datos del Select y solo deja la raza.
    }

    $(".especie").change(function(){
            $(".raza").html("<option value='0'>Otro...</option>"); // Limpia los datos del Select y solo deja la opcion "Otro..."
            var selectEspe = $('.especie').val();
            $.post({
                url: '/mascotas/dinamicQuery',
                method: 'POST',
                data: {
                    selectEspe,
                    _token: $('input[name="_token"]').val()
                }
            }).done(function(res){
                $(".raza").prop('disabled', false); // Elimina el atributo "disabled"
                var razas = JSON.parse(res);        // Lee el archivo Json
                $.each(razas, function(key, value){
                    var consulta = $(".raza").append('<option name="' + value.id + '">' + value.raza + '</option>');
                });
            });
        });
</script>
Victor
  • 5,493
  • 1
  • 27
  • 28