简体   繁体   中英

How can I select the item from the search dropdown and have it populate the search input field

If you type a word into the search input field a suggestion list appears below.

在此处输入图像描述

I would like to be able to select the word from the list eg Maine (ME) and have it then populate the search input field. How would I manipulate my code to be able to do this please?

HTML

<form action="*">
  <div class="form-group">
    <input type="text" class="rounded form-control" id="search" autocomplete="off" 
    placeholder="Current Location">
  </div>
<div id="match-list" onclick="myFunction()"></div>
</form>

javascript

const search = document.getElementById('search');
const matchList = document.getElementById('match-list');

// Search states.json and filter it
const searchPlaces = async searchText => {
    const res = await fetch('../data/states.json');
    const states = await res.json();

    // Get matches to current text input
    let matches = states.filter(state => {
        const regex = new RegExp(`^${searchText}`, 'gi');
        return state.name.match(regex) || state.abbr.match(regex);
    });

    if (searchText.length === 0) {
        matches = [];
        matchList.innerHTML = '';
    }
    outputHtml(matches);
};

// Show results in HTML
const outputHtml = matches => {
    if (matches.length > 0) {
        const html = matches.map(match => `
        <div class="card card-body mb-1">
        <h6>${match.name} (${match.abbr})</h6>
        </div>
        
        `).join('');
        matchList.innerHTML = html;
    }
};

search.addEventListener('keyup', () => searchPlaces(search.value));

function myFunction() {
    document.getElementById("search").innerHTML = "text";
  }

json

[
    {
        "abbr": "AL",
        "name": "Alabama",
    },
{
        "abbr": "ME",
        "name": "Maine",
    }
]

Found I needed to put value="" into the html file

 <input type="search" class="rounded form-control" id="search" autocomplete="off" placeholder="Current Location" value="">

and to update the following function in the javascript file.

function myFunction() {
    let texts = document.querySelector("h6").innerText;
    document.getElementById("search").value = texts;
    matchList.innerHTML = '';
  }

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