简体   繁体   English

如何使用JQuery填充来自link元素的HTML输入的值

[英]How to fill the value of HTML input from link element using JQuery

I have input and I suggest autocomplete list of words from my database using Ajax. 我有输入,我建议使用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. 我使用bootstrap 4来设计列表,但是使用<a></a>标记而不是<li></li>标记,因为当我使用<a>而不是<li>元素时,bootstrap 4提供了悬停效果清单。

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: 我的HTML看起来像这样:

<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>

you can add a clickHandler to your anchors, see this for more information. 您可以将clickHandler事件添加到您的锚,看到这个以获取更多信息。

The clickHandler would then basically use the innerHTML of the clicked a-element and fill any other element's content. 然后,clickHandler将基本上使用所单击的a元素的innerHTML并填充其他任何元素的内容。

<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;
}

If you are having issue in setting the value of input field then you should check val() 如果在设置输入字段的值时遇到问题,则应检查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? 如果在为动态生成的链接附加单击处理程序时遇到问题,则应检查以下现有问题: 动态创建的元素上的事件绑定?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM