0

I have input and I suggest autocomplete list of words from my database using Ajax. I use bootstrap 4 to design the list, but use <a></a> tag instead of the <li></li> tag, because bootstrap 4 provides hover effect when using <a> instead of <li> element for my list.

Everything is working the list of words is displaying, but I don't know how to fill the value of the input when, the user clicks on the desired word.

My HTML looks like this:

<form action="index.html" method="post">
        <div class="form-group">
          <label for="team1">First Team</label>
          <input id="team1" type="text" name="team1">
          <div id="autoFil" class="list-group col-sm-12"></div>
            //Here I generate the list using Ajax which looks like this

            <a class="list-group-item list-group-item-action ">Keyword 1</a>
            <a class="list-group-item list-group-item-action ">Keyword 2</a>
            <a class="list-group-item list-group-item-action ">Keyword n</a>
         </div>
</form>

3 Answers3

0

you can add a clickHandler to your anchors, see this for more information.

The clickHandler would then basically use the innerHTML of the clicked a-element and fill any other element's content.

Patrick M
  • 113
  • 1
  • 7
0
<form action="index.html" method="post">
        <div class="form-group">
          <label for="team1">First Team</label>
          <input id="team1" type="text" name="team1">
          <div id="autoFil" class="list-group col-sm-12"></div>
            //Here I generate the list using Ajax which looks like this

            <a class="list-group-item list-group-item-action " onclick="fillInput('Keyword 1')">Keyword 1</a>
            <a class="list-group-item list-group-item-action " onclick="fillInput('Keyword 2')">Keyword 2</a>
            <a class="list-group-item list-group-item-action " onclick="fillInput('Keyword n')">Keyword n</a>
         </div>
</form>
<script>
    function fillInput(val){
       document.getElementById('team1').value = val;
}
twitch
  • 225
  • 1
  • 13
0

If you are having issue in setting the value of input field then you should check val()

It is used like:

$('#team1').val('whatever value you want to set');

If you are having issue in attaching a click handler for dynamically generated links, then you should be checking this existing question: Event binding on dynamically created elements?

Vivek Athalye
  • 2,974
  • 2
  • 23
  • 32