简体   繁体   English

我怎样才能 select 搜索下拉列表中的项目并让它填充搜索输入字段

[英]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.我希望能够输入 select 列表中的单词,例如缅因州 (ME) ,然后将其填充到搜索输入字段中。 How would I manipulate my code to be able to do this please?我将如何操作我的代码才能做到这一点?

HTML 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 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 json

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

Found I needed to put value="" into the html file发现我需要将value=""放入 html 文件中

 <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.并在 javascript 文件中更新以下 function。

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

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

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