Mike Pistachio
Mike Pistachio

Reputation: 23

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/

Upvotes: 0

Views: 395

Answers (2)

gmurano
gmurano

Reputation: 36

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

Upvotes: 2

Sriram
Sriram

Reputation: 1738

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

Upvotes: 3

Related Questions