I am trying to autocomplete data using the bootstrap typeahead.
The idea is that, when you write a code in the input, do a search from the database. When selecting one of them, I automatically fill in the code and the name.
I tried to do it, but I have not succeeded, can someone help me?
This is my HTML code
<div class="form-group">
<div class="col-sm-11">
<label for="cuenta_codigo" class="col-sm-2 control-label">Cuenta Contable:</label>
<div class="col-sm-3">
<form:input id="cuenta_codigo" path="cuenta.ccuenta_cod" cssClass="form-control" placeholder="Código" autocomplete="off" data-provide="typeahead"/>
</div>
<div class="col-sm-6">
<form:input id="cuenta_nombre" path="cuenta.vcuenta_nombre" cssClass="form-control" placeholder="Nombre" />
</div>
</div>
</div>
This on my Controller
@RequestMapping(value = "/master/cuenta/ajax", produces = MediaType.APPLICATION_JSON_VALUE)
public List<AutoType> getAjax(@RequestParam("type") String type, @RequestParam("param") String param){
List<AutoType> lista = new ArrayList<>();
try {
lista = cuentaService.getCuentaAjaxByCode(param);
} catch (Exception e) {
logger.error(e);
}
return lista;
}
This is my JavaScript Code
<script>
$(document).ready(function () {
$('#cuenta_codigo').typeahead({
source: function (request, response) {
$.ajax({
url: "/master/cuenta/ajax",
type: "POST",
data: {
param: request.param
},
dataType: "json",
success: function (data) {
response(data);
}
});
}
});
});
</script>
If necessary I leave you the DAO Implement and the Service Implement
Dao Implement
@Override
public List<Cuenta> getCuentaAjax(String code) {
String namedQuery = "Cuenta.getAjaxByCode";
List<FilterHQL> filters = new ArrayList<>();
filters.add(new FilterHQL("ccuenta_cod", code+"%"));
return hibernateUtil.fetchListByParamHQL(filters, Cuenta.class, namedQuery);
}
Service Implement
@Override
public List<AutoType> getCuentaAjaxByCode(String code) {
List<AutoType> json = new ArrayList<>();
List<Cuenta> lista = cuentaDao.getCuentaAjax(code);
for (Cuenta cuenta : lista) {
json.add(new AutoType(cuenta.getCcuenta_cod(), cuenta.getVcuenta_nombre()));
}
return json;
}