按钮触发下拉/输入自动完成

时间:2018-09-04 07:24:02

标签: javascript jquery html

我复制了一个autocomplete function from web3schools(包括我的更改(original)),它可以完美地处理输入本身。但现在我做了一个类似的新图标,当您单击输入字段旁边的按钮时,它也应该打开列表。但是它没有附加该函数创建的html元素

我没有收到任何错误,它通过完整的函数运行。.它只是没有创建我认为的HTML元素。

有人看到我在做什么错吗?

$(function() {
  var klantInput = document.getElementById('klantTextInput');
  var btn = document.getElementById('klanten-expand');
  autocompleteBtnToInput(btn, klantInput)
})

function autocompleteBtnToInput(btn, inp) {
  var arr = ['customer0.5', 'customer1', 'customer2', 'customer3', 'customer4', 'customer5', ];

  var currentFocus;

  /*execute a function when someone clicks on the button:*/
  btn.addEventListener("click", function(e) {
    var a, b, i, val = inp.value;
    /*close any already open lists of autocompleted values*/
    closeAllLists();
    currentFocus = -1;
    /*create a DIV element that will contain the items (values):*/
    a = document.createElement("DIV");
    a.setAttribute("id", inp.id + "autocomplete-list");
    a.setAttribute("class", "autocomplete-items");
    /*append the DIV element as a child of the autocomplete container:*/
    console.log(a);
    this.parentNode.appendChild(a);
    /*for each item in the array...*/
    for (i = 0; i < arr.length; i++) {
      /*check if the item starts with the same letters as the text field value:*/
      if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
        /*create a DIV element for each matching element:*/
        b = document.createElement("DIV");
        b.setAttribute("class", "item");
        /*make the matching letters bold:*/
        b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
        b.innerHTML += arr[i].substr(val.length);
        /*insert a input field that will hold the current array item's value:*/
        b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
        /*execute a function when someone clicks on the item value (DIV element):*/
        b.addEventListener("click", function(e) {
          /*insert the value for the autocomplete text field:*/
          inp.value = inp.getElementsByTagName("input")[0].value;
          /*close the list of autocompleted values,
          (or any other open lists of autocompleted values:*/
          closeAllLists();
        });
        console.log(b);
        console.log(a);
        a.appendChild(b);
      }
    }
  });
  /*execute a function presses a key on the keyboard:*/
  btn.addEventListener("keydown", function(e) {
    var x = document.getElementById(this.id + "autocomplete-list");
    if (x) x = x.getElementsByTagName("div");
    if (e.keyCode == 40) {
      /*If the arrow DOWN key is pressed,
      increase the currentFocus variable:*/
      currentFocus++;
      /*and and make the current item more visible:*/
      addActive(x);
    } else if (e.keyCode == 38) { //up
      /*If the arrow UP key is pressed,
      decrease the currentFocus variable:*/
      currentFocus--;
      /*and and make the current item more visible:*/
      addActive(x);
    } else if (e.keyCode == 13) {
      /*If the ENTER key is pressed, prevent the form from being submitted,*/
      e.preventDefault();
      if (currentFocus > -1) {
        /*and simulate a click on the "active" item:*/
        if (x) x[currentFocus].click();
      }
    }
  });

  function addActive(x) {
    /*a function to classify an item as "active":*/
    if (!x) return false;
    /*start by removing the "active" class on all items:*/
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    /*add class "autocomplete-active":*/
    x[currentFocus].classList.add("autocomplete-active");
  }

  function removeActive(x) {
    /*a function to remove the "active" class from all autocomplete items:*/
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
  }

  function closeAllLists(elmnt) {
    /*close all autocomplete lists in the document,
    except the one passed as an argument:*/
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
        x[i].parentNode.removeChild(x[i]);
      }
    }
  }
}
.klantTextInput {
  position: relative;
  display: inline-block;
  width: calc(50% - 18px);
  display: inline-block;
  float: left;
  border-right: 0;
  border-bottom-right-radius: 0;
  border-top-right-radius: 0;
  outline: none;
}

.klantTextInput:focus {
  border: 1px solid rgb(164, 164, 164);
}

.klanten-expand {
  border-bottom: 1px solid rgb(204, 204, 204);
  margin-top: 1px;
  width: 18px;
  height: 20px;
  background-color: green;
  display: inline-block;
  overflow: hidden;
}

.klantTextInput:hover+.klanten-expand,
.klanten-expand:hover {
  background-position: -54px -176px;
}

.klantTextInput:active+.klanten-expand,
.klanten-expand:active,
.klantTextInput:focus+.klanten-expand,
.klanten-expand:focus {
  background-position: -90px -176px;
}

.autocomplete-items {
  position: absolute;
  border: 1px solid #d4d4d4;
  border-bottom: none;
  z-index: 99;
  /*position the autocomplete items to be the same width as the container:*/
  top: 100%;
  left: 0;
  right: 0;
  border-bottom: 1px solid #d4d4d4;
  max-height: 150px;
  overflow-y: auto;
}

.autocomplete-items .item {
  padding-left: 5px;
  cursor: pointer;
  background-color: #fff;
}

.autocomplete-items div:hover,
.autocomplete-active {
  color: #000;
  background-color: #c2c2c2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="klantTextInput" class="control-label col-md-2">klant:</label>
  <div class="col-md-4" style="height:21px;">
    <input type="text" id="klantTextInput" list="klanten" placeholder="Kies een klant" class="form-control klantTextInput" />
    <div class="klanten-expand" id="klanten-expand"></div>
  </div>
</div>

编辑


我还将接受(甚至可能更喜欢)的一种方法是保留用于输入字段klantTekstInput的{​​{3}}并通过单击按钮然后聚焦inputfield来触发它,依次触发eventListener("focus")

1 个答案:

答案 0 :(得分:0)

请您检查一下, 您忘记为klantTextInput输入父div分配“自动完成”类, 我已经更新了您的代码片段。

检查下面的图像。

enter image description here

$(function() {
  var klantInput = document.getElementById('klantTextInput');
  var btn = document.getElementById('klanten-expand');
  autocompleteBtnToInput(btn, klantInput)
})

function autocompleteBtnToInput(btn, inp) {
  var arr = ['customer0.5', 'customer1', 'customer2', 'customer3', 'customer4', 'customer5', ];

  var currentFocus;

  /*execute a function when someone clicks on the button:*/
  btn.addEventListener("click", function(e) {
    var a, b, i, val = inp.value;
    /*close any already open lists of autocompleted values*/
    closeAllLists();
    currentFocus = -1;
    /*create a DIV element that will contain the items (values):*/
    a = document.createElement("DIV");
    a.setAttribute("id", inp.id + "autocomplete-list");
    a.setAttribute("class", "autocomplete-items");
    /*append the DIV element as a child of the autocomplete container:*/
    
    this.parentNode.appendChild(a);
    /*for each item in the array...*/
    for (i = 0; i < arr.length; i++) {
      /*check if the item starts with the same letters as the text field value:*/
      if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
        /*create a DIV element for each matching element:*/
        b = document.createElement("DIV");
        b.setAttribute("class", "item");
        /*make the matching letters bold:*/
        b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
        b.innerHTML += arr[i].substr(val.length);
        /*insert a input field that will hold the current array item's value:*/
        b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
        /*execute a function when someone clicks on the item value (DIV element):*/
        b.addEventListener("click", function(e) {
          /*insert the value for the autocomplete text field:*/
          inp.value = inp.getElementsByTagName("input")[0].value;
          /*close the list of autocompleted values,
          (or any other open lists of autocompleted values:*/
          closeAllLists();
        });
        a.appendChild(b);
      }
    }
  });
  /*execute a function presses a key on the keyboard:*/
  btn.addEventListener("keydown", function(e) {
    var x = document.getElementById(this.id + "autocomplete-list");
    if (x) x = x.getElementsByTagName("div");
    if (e.keyCode == 40) {
      /*If the arrow DOWN key is pressed,
      increase the currentFocus variable:*/
      currentFocus++;
      /*and and make the current item more visible:*/
      addActive(x);
    } else if (e.keyCode == 38) { //up
      /*If the arrow UP key is pressed,
      decrease the currentFocus variable:*/
      currentFocus--;
      /*and and make the current item more visible:*/
      addActive(x);
    } else if (e.keyCode == 13) {
      /*If the ENTER key is pressed, prevent the form from being submitted,*/
      e.preventDefault();
      if (currentFocus > -1) {
        /*and simulate a click on the "active" item:*/
        if (x) x[currentFocus].click();
      }
    }
  });

  function addActive(x) {
    /*a function to classify an item as "active":*/
    if (!x) return false;
    /*start by removing the "active" class on all items:*/
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    /*add class "autocomplete-active":*/
    x[currentFocus].classList.add("autocomplete-active");
  }

  function removeActive(x) {
    /*a function to remove the "active" class from all autocomplete items:*/
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
  }

  function closeAllLists(elmnt) {
    /*close all autocomplete lists in the document,
    except the one passed as an argument:*/
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
        x[i].parentNode.removeChild(x[i]);
      }
    }
  }
}
.klantTextInput {
  position: relative;
  display: inline-block;
  width: calc(50% - 18px);
  display: inline-block;
  float: left;
  border-right: 0;
  border-bottom-right-radius: 0;
  border-top-right-radius: 0;
  outline: none;
}

.klantTextInput:focus {
  border: 1px solid rgb(164, 164, 164);
}

.klanten-expand {
  border-bottom: 1px solid rgb(204, 204, 204);
  margin-top: 1px;
  width: 18px;
  height: 20px;
  background-color: green;
  display: inline-block;
  overflow: hidden;
}

.klantTextInput:hover+.klanten-expand,
.klanten-expand:hover {
  background-position: -54px -176px;
}

.klantTextInput:active+.klanten-expand,
.klanten-expand:active,
.klantTextInput:focus+.klanten-expand,
.klanten-expand:focus {
  background-position: -90px -176px;
}

.autocomplete-items {
  position: absolute;
  border: 1px solid #d4d4d4;
  border-bottom: none;
  z-index: 99;
  /*position the autocomplete items to be the same width as the container:*/
  top: 100%;
  left: 0;
  right: 0;
  border-bottom: 1px solid #d4d4d4;
  max-height: 150px;
  overflow-y: auto;
}

.autocomplete-items .item {
  padding-left: 5px;
  cursor: pointer;
  background-color: #fff;
}

.autocomplete-items div:hover,
.autocomplete-active {
  color: #000;
  background-color: #c2c2c2;
}
.klantTextInputautocomplete-list {
    position: absolute;
    border: 1px solid #d4d4d4;
    border-bottom: none;
    border-top: none;
    z-index: 99;
    top: 100%;
    left: 0;
    right: 0;
}
.autocomplete {
    position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="klantTextInput" class="control-label col-md-2">klant:</label>
  <div class="col-md-4 autocomplete" style="height:21px;">
    <input type="text" id="klantTextInput" list="klanten" placeholder="Kies een klant" class="form-control klantTextInput" />
    <div class="klanten-expand" id="klanten-expand"></div>
  </div>
</div>