Autocomplete an input dependent on another

1

I have the following: a form with a customer fields and another appliance field in the database, each device is related to a customer by means of the primary customer key.

what I need: At this moment I already have the completed car running in the client input:

Html:

 <div class="col-md-4">
      <div class="form-group">
      <label for="cliente">Cliente <span style="color:red;">*</span></label>
      <input id="cliente1" class="span12 form-control" type="text" name="cliente1" placeholder="Ingrese Cliente" value=""  />
      <input id="cliente_id" class="span12" type="hidden" name="clientes_id" value="0"  />
 </div>

Js:

 $("#cliente1").autocomplete({
        source: "<?php echo base_url(); ?>os/autoCompleteCliente",
        minLength: 1,
        select: function( event, ui ) {
             $("#clientes_id").val(ui.item.id);


        }
  });

Now, what is the problem? ... I explain:

Up there you see another input from id equivalent to "client_id" (this field fills up when I select an autocomplete option) what I want is that this field here below the name = Ename:

<div class="form-group">
     <label for="nombreE">Nombre/Equipo/Marca/Modelo/Nº Serie (Ej. Pc de Juan/Portatil/Sony/SVG31S) </label>
     <input name="nombreE" type="text" class="form-control" id="acnombreE" placeholder="Ingrese Nombre, Tipo, Marca, Modelo o Serie" value="">
     <input id="aparatosid" class="span12" type="hidden" name="aparatosid" value=""  />
</div>

Autocomplete in the same way, but taking into account two things:

  • What I am writing in the
  • What is in the client_id field
  • but I can not find the way to send those 2 parameters using the jquery autocomplete since jquery only sends me a single parameter named term

    This is the js function that I use to autocomplete the field in question, but it throws me all devices that look like what I write in the field, so I need to filter so that only the devices related to the client I selected above:

        $("#acnombreE").autocomplete({            
            source: "<?php echo base_url(); ?>os/autoCompleteaparato
            minLength: 1,
            select: function( event, ui ) {
                 $("#aparatosid").val(ui.item.id);
                 $("#actipoE").val(ui.item.tipoE);
                 $("#acmarcaE").val(ui.item.marcaE);
                 $("#acmodeloE").val(ui.item.modeloE);
                 $("#acn_serieE").val(ui.item.n_serieE);
    
    
            }
      });
    

    Somebody can help me out how I can autocomplete this field and show me suggestions as I write, using the aforementioned field ('client_id') as a second filter,

    thank you very much.

        
    asked by Yilmer Avila Villarreal 29.07.2017 в 23:02
    source

    1 answer

    0

    Currently I struggle with this mess a few days ago and looking online I found an example, which helped me.

    I use this JavaScript file to listen to the form in html (I have the form in a div with id client:

    $(function(){
       /* Ponemos evento blur a la escucha sobre id nombre en id cliente. */
       $('#cliente').on('blur','#operador',function(){
          /* Obtenemos el valor del campo */
          var valor = this.value;
          /* Si la longitud del valor es mayor a 2 caracteres.. */
          if(valor.length>=3){
    
             /* Cambiamos el estado.. */
             $('#estadoOperador').html('Cargando datos del operador desde servidor...');
    
             /* Hacemos la consulta ajax */
             var consulta = $.ajax({
                type:'POST',
                url:'operador.php',
                data:{operador:valor},
                dataType:'JSON'
             });
    
             /* En caso de que se haya retornado bien.. */
             consulta.done(function(data){
                if(data.error!==undefined){
                   $('#estadoOperador').html('Ha ocurrido un error: '+data.error);
                   return false;
                } else {
                   if(data.idoperador!==undefined){$('#cliente #idoperador').val(data.idoperador);}
                   $('#estadoOperador').html('Datos del operador cargados..');
                   return true;
                }
             });
    
             /* Si la consulta ha fallado.. */
             consulta.fail(function(){
                $('#estadoOperador').html('Ha habido un error contactando el servidor.');
                return false;
             });
    
          } else {
             /* Mostrar error */
             $('#estadoOperador').html('El nombre tener una longitud mayor a 2 caracteres...');
             return false;
          }
       });
    });
    

    and then operator.php where I make the call to the database and search in my database

    <?php
    
    /* Conectar a una base de datos de MySQL invocando al controlador */
    $dsn = 'mysql:dbname=dbsistema;host=localhost';
    $usuario = 'root';
    $contraseña = '';
    
    try {
        $gbd = new PDO($dsn, $usuario, $contraseña);
    } catch (PDOException $e) {
        echo 'Falló la conexión: ' . $e->getMessage();
    }
    
    if(!empty($_POST['operador']))
    { 
    
        $nombre = $_POST['operador'];
        $sql = "SELECT * FROM operadores WHERE nombre = :nombre";  
        $stmt = $gbd->prepare($sql);
        $stmt->bindValue(":nombre",$nombre);
        $stmt ->execute();
        $arrDatos = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
        //Verifica si no hay datos en la consulta
        if($arrDatos){
        foreach ($arrDatos as $row) {
          if ($nombre = $row['nombre']) {
            $return = array ('idoperador'=>$row['numero']);
          }      
        }
    
    } else {
            //Esto ocurre si el nombre está vacío solamente
            $arrDatos = array('error'=>'El nombre está vacío');
    }
    //Imprimir los resultados 
    die(json_encode($return));
    }
    
        
    answered by 30.07.2017 / 23:36
    source