【问题标题】:Creating a Search using JavaScript使用 JavaScript 创建搜索
【发布时间】:2021-10-10 21:15:38
【问题描述】:

我正在尝试使用 JavaScript 创建搜索。我已经创建了框架,但不确定如何在用户单击下拉项目时使用所选选项填充输入字段。我该怎么办?这是我的代码:

HTML:

<input class="form-control searchResult" type="text" id="search" placeholder="Search">

<div id="match-list"></div>

JS:

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

const searchStates = async searchText => {
    const res = await fetch('countries.json');
    const states = await res.json();

    let matches = states.filter(state => {
        const regex = new RegExp(`^${searchText}`, 'gi');
        return state.name.match(regex);
    })

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

    if (matches.length > 0) {
        const html = matches.map((match, i) => `<div class="dropdown" id="dropdown${i}"><option class="dropdown-text" id="dropdown-text${i}">${match.name}</option></div>`).join('');

        console.log(html);
        matchList.innerHTML = HTML;
    }

}

search.addEventListener('input', () => searchStates(search.value));

JSON:

[
  {
  "name":"Afghanistan",
  "phoneCode":"+93",
  "capital":"Kabul",
  "abbr":"AFG"
  },
  {
  "name":"Albania",
  "phoneCode":"+355",
  "capital":"Tirana",
  "abbr":"ALB"
  },
  {
  "name":"Algeria",
  "phoneCode":"+213",
  "capital":"Algiers",
  "abbr":"DZA"
  }
]

【问题讨论】:

标签: javascript html css json search


【解决方案1】:

使用datalist 标签可能会更好。这将直接过滤结果并对点击事件做出反应:

html:

<input id="country-input list="countries">
<datalist id="countries"></datalist>
<button onClick="send">Send</button>

js:

// Store countries array in COUNTRIES
const inputDataList = document.getElementById("countries");

COUNTRIES.forEach((country) => {
  const countryOption = document.createElement("option");
  countryOption.value = country.name;
  inputDataList.appendChild(countryOption);
});

要读取输入值,只需从 input 元素中获取.value

const countryInput = document.getElementById("country-input");

const sendCountry = () => {
    // Do stuff with countryInput.value
    console.log(countryInput.value);
};

【讨论】:

  • 这绝对有效,我已经实现了。所以现在,为了获得用户选择的内容,我必须获取 标记的值,对吗?或者我会获取 标签的值吗?
  • 您将获取输入标签的值。我已经编辑了我的答案;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-12
  • 2020-07-28
  • 2020-10-27
  • 1970-01-01
  • 2013-06-07
相关资源
最近更新 更多