首页 > 解决方案 > 一个 href onclick 附加到输入

问题描述

我正在尝试创建一个消息系统,到目前为止它几乎完成了,只是发送消息需要一个小的编辑。我已经为接收器创建了一个实时搜索并且它正在工作,一切都在显示,但我想制作一个点击功能来将接收器的名称附加到输入中。

示例图像

或者有什么方法可以在输入用户名时更改占位符?

这是自动完成脚本:

$(document).ready(function(){
    $('#to input[type="text"]').on("keyup input", function(){
        /* Get input value on change */
        var inputVal = $(this).val();
        var resultDropdown = $(this).siblings(".result");
        if(inputVal.length){
            $.get("engine/includes/message_to_autocomplete.php", {term: inputVal}).done(function(data){
                // Display the returned data in browser
                resultDropdown.html(data);
            });
        } else{
            resultDropdown.empty();
        }
    });


    $(document).on("click", ".result p", function(){
        $(this).parents("#to").find('input[type="text"]').val($(this).text());
        $(this).parent(".result").empty();
    });
});

它返回:$row['username']如图所示。

标签: javascriptjquery

解决方案


似乎您正在尝试重新发明轮子。由于您已经在使用 jquery,您可以尝试autocomplete

$(function() {
    var names = ["Austin", "Bryson", "Claudia", "David", "Eve", "Fabio", "Garry", "Helen"];

    $("#to").autocomplete({ source: names });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<input id="to" type="text" placeholder="Name"/>

至于更改占位符,有一个名为typeahead的库,您可以在此处找到大量演示


推荐阅读