首页 > 解决方案 > 每次用户单击下拉列表中的项目时,都会读取它的值并将其放入输入字段中

问题描述

请访问页面查看问题https://ibnul.neocities.org/_temporary/index10-prb2.html

在这里,我有一个输入字段,当您单击它时,它将显示一个包含一些列表项的下拉列表。如果用户单击列表中的项目,它应该显示在输入字段中。如果用户再次单击列表中的另一个项目,它应该再次显示在输入字段中,覆盖前一个项目。几乎就像一个选择选项标签行为。

我的意思是用户单击的该项目的文本值应显示在输入字段中,并且列表将消失。

谁能告诉我如何编写这个脚本。请用纯javascript显示。

var zip_list_show_Btn = document.querySelector('.ziplist-show-btn');
var zip_list_con = document.querySelector('.zip-list-con');

zip_list_show_Btn.addEventListener('focus', showZiplistCon);

function showZiplistCon() {
  zip_list_con.classList.add('show-zip-list-con');
}

window.addEventListener("click", function(event) {
  if (!event.target.matches('.ziplist-show-btn')) {
    var langDropdowns = document.getElementsByClassName('zip-list-con');
    for (var i = 0; i < langDropdowns.length; i++) {
      var openlangDropdown = langDropdowns[i];
      if (openlangDropdown.classList.contains('show-zip-list-con')) {
        openlangDropdown.classList.remove('show-zip-list-con');
      }
    }
  }
});
* {
  margin: 0px;
}

body {
  padding: 50px;
  display: flex;
  justify-content: center;
}

.zip-input {
  width: 100px;
  padding: 10px 5px 10px 5px;
  margin: 5px 10px 5px 10px;
  font-size: 14px;
  border: 1px solid rgb(179, 179, 179);
  color: rgb(172, 172, 172);
  -webkit-appearance: none;
}

.zip-input::placeholder {
  color: #acacac;
  opacity: 1;
}

.zip-input-ziplist-con {
  position: relative;
  display: flex;
}

.zip-list-con {
  flex-grow: 2;
  position: absolute;
  z-index: 1;
  top: 53px;
  right: 0px;
  width: 160px;
  height: 200px;
  overflow-x: hidden;
  overflow-y: scroll;
  background-color: white;
  border: 0.9px solid lightgray;
  display: none;
}

.zip-listitem {
  cursor: default;
  padding: 5px 5px 5px 10px;
  font-size: 14px;
  color: #acacac;
}

.zip-listitem:hover {
  background-color: #228de4;
  color: white;
}

.show-zip-list-con {
  display: block;
}
<div class='zip-input-ziplist-con'>
  <input class='zip-input radi-show-btn ziplist-show-btn' type='text' placeholder='Zip/City'>
  <div class='zip-list-con'>
    <p class='zip-listitem'>43748 NewYork</p>
    <p class='zip-listitem'>43748 Italy</p>
    <p class='zip-listitem'>43748 French</p>
    <p class='zip-listitem'>43748 Australia</p>
    <p class='zip-listitem'>43748 something</p>
    <p class='zip-listitem'>43748 something</p>
    <p class='zip-listitem'>43748 something</p>
    <p class='zip-listitem'>43748 something</p>
    <p class='zip-listitem'>43748 something</p>
  </div>
</div>

标签: javascripthtmlcss

解决方案


按照您编写代码的方式,目标是获取单击的文本并将该值放入您的输入元素中。所以,只需在你的 eventListener 回调函数中添加这个块。

if (event.target.matches('.zip-listitem')) {
    var selectedText = event.target.textContent;
    document.getElementsByClassName("zip-input")[0].value = selectedText;
}

推荐阅读