简体   繁体   English

将输入文本框中的文本替换为所选自动完成选项中的文本

[英]Replace the text in an input text box with text from a selected autocomplete option

I have an input type text box with and auto complete options below it.我有一个输入类型文本框,下面有自动完成选项。 Using the up and down arrows on the keyboard, you can move through the auto complete options and "select" one, making it turn red.使用键盘上的向上和向下箭头,您可以在自动完成选项中移动并“选择”一个,使其变为红色。 How do I replace the text in the input box with the text of the selected option like is common place with search engines?如何将输入框中的文本替换为所选选项的文本,这在搜索引擎中很常见?

<input class="searchBox" id="searchBox" name="q" type="text" autocomplete="off" placeholder="hi">

<div class="autoSuggestContainer">
  <span>Select from Menu</span>
    <a>history</a>
    <a>hilton</a>
    <a>hip2save</a>
    <a>hillary clinton</a>
    <a>hickok45</a>
    <a>hitler</a>
    <a>hibiscus</a>
    <a>hipaa</a>
</div>

Here is a link to the code with the HTML, CSS, and Javascript: https://jsfiddle.net/qckyu5e6/ Here is a link to the code with the HTML, CSS, and Javascript: https://jsfiddle.net/qckyu5e6/

As soon as you set the selected class on move up and down you can retrieve the anchor tag with selected class text and assign it to the input tag.一旦您在上下移动时设置了选定的 class,您就可以使用选定的 class 文本检索锚标记并将其分配给输入标记。 https://jsfiddle.net/b19uv25q/6/ https://jsfiddle.net/b19uv25q/6/

    $("#searchBox").val($(".selected").text());

Following your fiddle you'll achieve that doing just this按照你的小提琴,你会做到这一点

$('.searchBox').val($(".selected").text());

If you want to trigger it you need to add a new case to handle 'enter' key on your keyDown event and also a click event如果你想触发它,你需要添加一个新的案例来处理你的 keyDown 事件的“输入”键以及一个点击事件

document.onkeydown = function (e) {
  e.preventDefault();
  
  switch (e.keyCode) {
    case 38:
      moveUp();
      break;      
    case 40:   
      moveDown();
      break;
    case 13:
      //handle enter key
      setInputText($(".selected").text());
      break;
    }
};

$(".urlnamelinkAS").on("click", function () {
    setInputText($(this).text());
});

function setInputText(text){
    $('.searchBox').val(text);
}

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

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