简体   繁体   中英

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/

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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