Filter a Select2 by selecting an ion in another

Asked

Viewed 277 times

1

I have a field of type Select2 that is bringing me all the customers of a database. As I do, when selecting a client, in another Lect2 appear only contracts of the selected customer, I can not think of a solution for this, I do not have much knowledge about Ajax. EDITED

  $('#cliente').on('select2:selecting', function (e) {
$.get("orcamentocliente/"+$('#cliente').val(), function(data) {
  data = JSON.parse(data);
  for (var i = 0; i < data.length; i++) {
    $('#orcamentos').append($('<option>', {value:data[i].id, text:data[i].descricao+'-'+data[i].dataorcamento})).trigger('change');
  }
})
  .fail(function() {
    alert( "Erro ao carregar os orçamentos" );
  })

I created this 'orcamentoclient/' route and pass the client ID. For a function in the controller that I created, however, when I click on the client appears his right, but when I click on another client appears the of all. Below the client select code:

<div class="form-group col-sm-6">
                        {{ Form::label('cliente', 'Cliente') }}
                        <select class="js-example-basic-single" data-style="form-control" name="cliente_id" id="cliente" required="required">
                          <option> Selecione o cliente</option>
                          @forelse ($clientes as $cliente)
                          <option value="{{ $cliente->id }}">{{ $cliente->razaosocial }}</option>
                          @empty
                          <option value="">Nenhum item cadastrado</option>
                          @endforelse
                        </select>
                    </div>
  • The ideal is AJAX even, you already have something ready?

  • I am trying to bring all records and filter using Select2 using a Jquery function.

  • Put what you can of code to make it easier to mount an example

  • Good for now it looks like this: $('#customer'). on('Select2:Selecting', Function(e) { //Ajax $.get( "orcamentocliente/"+$('#client'). val(), Function(data) { data = JSON.parse(data); for (var i = 0; i < data.length; i++) { $('#budgets'). append($('<option>', {value:data[i]. id, text:date[i]. Description+'-'+data[i]. dating}). Trigger('change'); } }) . fail(Function() { Alert( "Error loading budgets" ); }) });

  • For easy reading, add the code by editing the question.

  • Ready kkk, edited

Show 1 more comment

1 answer

0


JS

<script>
    $('#cliente').change(function(){
        $.ajax({
            url: '{{ route('sua_rota') }}',
            type: 'POST',
            data: {
               _token: '{{ csrf_token() }}',
               cliente_id: $('#cliente').val(),
            },
            dataType: 'JSON',
            success: function(data){
                if (data.success) {
                    $.each(data.options, function (i, item) {
                        $('#seuSelect').append($('<option>', { 
                            value: item.value,
                            text : item.text 
                        }));
                    });
                } else {
                    // Aqui trata se algo deu errado no servidor
                }
            },
            error: function() {
                // Aqui trata se algo deu errado na requisição AJAX
            }
         });
    });
</script>

ROUTE

Route::post('sua_rota', 'SeuController@SeuMetodo')->name('sua_rota');

CONTROLLER

public function SeuMetodo(Request $request)
{
    $variavel = SeuModelo::find($request->cliente_id);

    // Sua lógica

    $options = //<-- AQUI VAI ARRAY DAS OPÇÕES DO SELECT [['value'=> $valor, 'text' => $text],['value'=> $valor, 'text' => $text]]

    if ($logica) { // <-- Se tudo deu certo na busca dos options
        return json_encode([ 'success' => true, 'options' => $options ]);
    } else { <-- Se alguma coisa deu errado na busca dos options
        return json_encode([ 'success' => false, 'options' => false ]);
    }
}
  • Wow! It went super well, thank you so much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.