Create autocomplete in jQuery placeholder

1

I would like to know how to create an autocomplete in the placeholder of an input, in my example it only shows the data and autocomplete but I would like that same data to be shown in the placeholder. How it is shown in the image

This is my code

    function Datas() {
    $.ajax({
        url: "Datas",
        dataType: "JSON",
        success: function (data) {
            console.log(data);
            var Datasarray = [];
            for (var i = 0; i < data.length; i++) {
                Datasarray .push(data[i].LockNumber)
            }

            $("input#filterData").autocomplete(
                {
                    source: Datasarray ,
                    selectFirst: true,
                    minLength: 3 
                }


            );


        }
    })
}



 <div class="input-group col-lg-4" style="height:50%;">
        <input name="filterData" type="text" id="filterData" class="form-control input-primary" placeholder="Buscar Datos" />

        <span class="input-group-btn">
            <button class="btn btn-info" type="submit" id="filter" >Buscar</button>
        </span>
    </div>
    
asked by Daniel 12.03.2018 в 21:42
source

1 answer

0

You can work them in this way. Where the result of the input matches the dictionary of your ajax. I'm not sure if your ajax will also be executed in the input events.

//Tu resultado del ajax
var names = [
  'John',
  'Miguel',
  'Hanna',
  'Pedro',
  'Alfredo',
  'Aaron'
];


var name = '';
$('#input').keyup(function(e) {
  var val = $(this).val();
  
  if(val == '') {
    $('#complete').text('');
    return;
  }

  if (e.which === 37 || e.which === 13) {
    e.preventDefault();
    $('#input').val(name);
    $('#complete').text('');
    return;
  }
  
  var find = false;
  for (var i = 0; i < names.length; i++) {
    name = names[i];
    if(name.indexOf(val) === 0) {
      find = true;
      break;
    } else {
      name = '';
    }
  }
  
  if(find === true) {
    $('#complete').text(name);
  } else {
    $('#complete').text('');
  }
})
body {
  direction: ltr;
  text-align: left;
}
body,
input,
textarea {
  font: 14px Tahoma, Verdana, Arial, sans-serif;
}
#container,
#input,
#complete{
  width: 512px;
  height: 32px;
  line-height: 32px;
  margin: 0 auto;
}
#container {
  position: relative;
}
#input,
#complete{
  position: absolute;
  top: 0;
  right: 0;
  padding: 0 8px;
  border: 2px solid #ddd;
  cursor: text;
}
#input:focus,
#complete:focus{
  outline: none;
  border-color: #aaa;
}
#input {
  color: #333;
  background-color: transparent;
}
#complete {
  color: #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div id="complete"></div>
  <input type="text" id="input" placeholder="Escriba estos nombres: John, Mike, Miguel, Hanna, Pedro, Alfredo, Aaron">
</div>
    
answered by 12.03.2018 в 22:47