A few days ago I discovered that with html you can do an autocomplete without using jQuery or any other tool and I did this:
categoryClubFutbol.php
<label for="club" class="form-label">Clubes</label>
<input type="text" class="form-control" name="club" id="club" list="miLista">
<datalist id="miLista">
<?php foreach($datos as $c){ ?>
<option value="<?=$c['id'];?>"><?=$c['club'];?></option>
<?php } ?>
</datalist>
It works fine, but the error I have is that if I select the club within it, input
it shows me id
and not the name of the team.
This is an example withoutPHP
<label for="club" class="form-label">Clubes</label>
<input type="text" class="form-control" name="nombre" id="club" list="miLista">
<datalist id="miLista">
<option value="1">Boca</option>
<option value="2">River</option>
<option value="3">Independiente</option>
<option value="4">Racing</option>
</datalist>
That's the behavior by design when you have a
value
.Instead of using the id inside the
value
, you could put the text with the team name and store the id in andata
extra property.From JavaScript there is no very direct way to get the
data-id
selected one, because a datalist is not associated with an input (and can be used on many different inputs). These would be the steps:What I did was: get the attribute
list="miLista"
and reference the element with that id (the datalist). Then, within that datalist, look for the option whosevalue
is equal to the value of the input. When obtaining the option, only there is thedata-id
.