Fill a Select of Laravel, with a Change event of another Select

0

How can I use the change event of a Form::select to fill in another Form::select ?

Example:

I charge a main Select with some departments:

Controller

$masterareas = dk_master_area::orderBy('name','asc')->get();
$data = array();
   foreach ($masterareas as $masterarea) {
      $areas = dk_area::where('id_master_area','=',$masterarea->id)->orderBy('name','asc')->get();
      $tdata = array();
      foreach ($areas as $area) {
          $tdata[$area->id] = $area->name;
      }
      $data[$masterarea->name] = $tdata;
    }
return view('user/create', ['areas'=>$data]);

View:

{!!Form::select('areas',$areas,null,['id'=>'areas','class'=>'form-control'])!!}

This is the result:

Depending on the area you choose, I must find the department in that area to charge the charges available to the Department, which at the base level are already related, so I can know what charge belongs to that department.

But I do not know how I can do, so when choosing an area, I can load in a second select, the charges. Should I use the same Form::select or simply a normal select? I do not want to have problems when trying to save the data.

    
asked by Maykol Rivas 16.03.2017 в 14:46
source

1 answer

1

I really do not know if you are using that select within a form (you say that after there are no conflicts when saving there is no problem) or not, but regardless of that you do this :

$.(document).ready(function($) {

      $.ajax({
          url: 'listar_areas', //ruta donde tengas la funcion listar areas
          type: 'GET',
          dataType: 'json'
        })
        .done(function(respuesta) {
            var response = respuesta;

            for (var i = response.length; i >= 0; i--) {
              $('#area_de_trabajo').append('<option value="' + response[i].id_area + '">' + response[i].area_descripcion + '</option>';
              }
            })
          .fail(function() {
            console.log("error");
          })

          $('#area_de_trabajo').change(function(e) {
            e.preventDefault();
            $.ajax({
                url: 'listar_cargos', //ruta donde enviaras el id del area para listar luego los cargos
                type: 'POST',
                dataType: 'json',
                data: {
                  'id_area': $(this).val();
                })
              .done(function(respuesta) {
                  var response = respuesta;

                  for (var i = 0; i < response.length; i++) {
                    $('#cargo').append('<option value="' + response[i].id_cargo + '">' + response[i].cargo_descripcion + '</option>';
                    }
                  })
                .fail(function() {
                  console.log("error");
                })
              });
          });
<select name="area_de_trabajo" id="area_de_trabajo">
    </select>

<select name="cargo" id="cargo">
    </select>
    
answered by 16.03.2017 / 15:05
source