pues bien tengo unas funciones que hacen que un input muestre sugerencias de nombres a medida que se escribe y esas sugerencias las trae de una base de datos y otra función que completa los datos restantes como son nit y profesión todo funciona pero al hacer un clone del contenedor de los inputs la función de crear sugerencias no se ejecuta cual puede ser mi error dejo los códigos
traer.php
este lo que hace es consultar los nombres o apellidos escritos en el input i traer los datos faltantes
<?php
if (isset($_POST['buscar'])) {
$names = $_POST['names'];
$valores = array();
$valores['existe'] = "0";
$workers = array();
//CONSULTAR
$resultados = mysqli_query($conexion, "SELECT * FROM `usuarios`
WHERE first_name COLLATE UTF8_SPANISH_CI LIKE '%$names%'
OR second_name COLLATE UTF8_SPANISH_CI LIKE '%$names%'
OR first_surname COLLATE UTF8_SPANISH_CI LIKE '%$names%'
OR second_surname COLLATE UTF8_SPANISH_CI LIKE '%$names%'
OR CONCAT(first_name,' ',second_name,' ',first_surname,' ',second_surname) COLLATE
UTF8_SPANISH_CI LIKE '%$names%'");
while ($consulta = mysqli_fetch_array($resultados)) {
$valores['existe'] = "1";
$valores['nombres'] = $consulta['first_name']."
".$consulta['second_name']."".$consulta['first_surname']." ".$consulta['second_surname'];
$valores['documento'] = $consulta['n_documento'];
$valores['cargo'] = $consulta['cargo_e'];
}
}sleep(1);$valores = json_encode($valores);echo $valores;?>
luego esta el workers.php
$valores = array();
$resultados = mysqli_query($conexion, "SELECT * FROM `usuarios` WHERE `status` = 'activo'");
while ($consulta = mysqli_fetch_array($resultados)) {
$valores = $consulta['first_name'] . " " . $consulta['second_name'] . " " . $consulta['first_surname'] . " " . $consulta['second_surname'].",";
echo $valores;
}
y este es el main.js
en este esta la función para generar las sugerencias, el clone del contenedor, la función para consultar los usuarios y crear un array con sus nombres y por ultimo la función de autocompletar
"use strict";
let autocomplete = (inp, arr) => {
/*the autocomplete function takes two arguments,
the text field element and an array of possible autocompleted values:*/
let currentFocus;
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function (e) {
let a, //OUTER html: variable for listed content with html-content
b, // INNER html: filled with array-Data and html
i, //Counter
val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) {
return false;
}
currentFocus = -1;
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items list-group text-left");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
b.setAttribute("class", "list-group-item list-group-item-action");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function (e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function (e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) {
//up
/*If the arrow UP key is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
let addActive = (x) => {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = x.length - 1;
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("active");
}
let removeActive = (x) => {
/*a function to remove the "active" class from all autocomplete items:*/
for (let i = 0; i < x.length; i++) {
x[i].classList.remove("active");
}
}
let closeAllLists = (elmnt) => {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
};
// ------------------------------------------------------------
// HASTA AQUI ES LO QUE GENERA LAS SUGERENCIAS
// ------------------------------------------------------------
// CLONAR LOS CAMPOS INICIO
var padre = document.getElementById('padreContenedor');
var btn_copy = document.getElementById('btnCopiar');
btn_copy.onclick = function(e){
e.preventDefault()
const hijo = document.getElementById('hijoContenedor')
const copia = hijo.cloneNode(true)
copia.querySelectorAll("input").forEach(e => e.value = "");
padre.insertAdjacentElement('beforeend', copia)
}
// CLONAR LOS CAMPOS FIN
// CONSULTAR A BD LOS NOMBRES DE LOS TRABAJADORES
$(document).ready(()=>{
$.post("workers.php",function(data){
let mydata = data
let workers = mydata.split(',')
// console.log(workers)
$('.busqueda').on('focus',()=>{
let myinput = $('#busqueda:focus')[0]
autocomplete(myinput, workers);
})
})
})
// CONSULTAR A BD LOS NOMBRES DE LOS TRABAJADORES FIN
// AUTOCOMPLETAR LOS CAMPOS INICIO
$('.busqueda').on('focus', (e) => {
$(this).on('keyup change blur', ()=>{
let names = $('.busqueda:focus').val();
// console.log(names)
var parametros = {
"buscar": "1",
"names": names
};
$.ajax({
data: parametros,
dataType: 'json',
url: 'traer.php',
type: 'post',
success: function(valores) {
if (valores.existe == "1" && names != "") { //Aqui usamos la variable que NO use en el vídeo
// $("#nombre").val(valores.nombre);
$('#busqueda:focus').parent().parent().children('.col-md-4').children('#ident').val(valores.documento);
$('#busqueda:focus').parent().parent().children('.col-md-4').children("#cargo").val(valores.cargo);
} else {
$('#busqueda:focus').parent().parent().children('.col-md-4').children('#ident').val('');
$('#busqueda:focus').parent().parent().children('.col-md-4').children("#cargo").val('');
}
}
})
})
})
// AUTOCOMPLETAR LOS CAMPOS FIN
Y EL HTML
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test Ajax</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.min.css">
</head>
<style>
</style>
<body>
<div class="card">
<div class="card-header">
<h5>Traer Datos</h5>
</div>
<div class="card-body" id="padreContenedor">
<div class="row g-3 mb-3" id="hijoContenedor">
<div class="col-md-4">
<input type="text" id="busqueda" class="busqueda form-control" placeholder="Nombres">
</div>
<div class="col-md-4">
<input type="text" id="ident" class="form-control ident" placeholder="N° de Identidad">
</div>
<div class="col-md-4">
<input type="text" id="cargo" class="form-control cargo" placeholder="Cargo / Rol">
</div>
</div>
</div>
<div class="card-footer">
<button class="btn btn-outline-dark" id="btnCopiar">Copiar</button>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js"></script>
<script src="main.js"></script>
</html>
he probado acceder a el input con clase e id busqueda de muchas maneras pero no estoy seguro si es porque este no se carga cuando carga el documento
body
. Te recomiendo mover el script de jquery a esa zona también (antes de los demás scripts).