根据预定列表自动填充为用户类型的文本区域

问题描述 投票:0回答:1

我有一个HTML格式的文本区域。当用户开始输入内容时,我想根据预填充列表(JSON)自动填充可能的匹配项列表。最后,用户可以only从这些选项之一中进行选择。如果没有超过一千种选择,那么使用下拉菜单是可行的。关于如何实现这一点的任何想法?还是从哪里开始?谢谢!

screenshot of a dropdown list that populates as the user types

javascript html json forms validation
1个回答
0
投票

[W3Schools中查看此示例。

我已经对其进行了修改,以从JS-Array创建Dropdown。我希望这是一个很好的起点。

var list = [{name: "Foo", link: "#foo"}, {name: "Bar", link: "#bar"}]

function myFunction() {
  var dopdownEl = document.getElementById("myDropdown");
  dopdownEl.classList.toggle("show");
  list.forEach(o => {
  	var el = document.createElement('a');
    el.innerHTML = o.name;
    el.href = o.link;
    dopdownEl.appendChild(el);
  });
}

function filterFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  div = document.getElementById("myDropdown");
  a = div.getElementsByTagName("a");
  for (i = 0; i < a.length; i++) {
    txtValue = a[i].textContent || a[i].innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
  }
}
#myInput {
  box-sizing: border-box;
  background-image: url('searchicon.png');
  background-position: 14px 12px;
  background-repeat: no-repeat;
  font-size: 16px;
  padding: 14px 20px 12px 45px;
  border: none;
  border-bottom: 1px solid #ddd;
}

#myInput:focus {outline: 3px solid #ddd;}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f6f6f6;
  min-width: 230px;
  overflow: auto;
  border: 1px solid #ddd;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {background-color: #ddd;}

.show {display: block;}
<div>
  <button onclick="myFunction()">Dropdown</button>
  <div id="myDropdown" class="dropdown-content">
    <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
  </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.