SO - 30750369

by pierian_design

HTML

<form id="form" onsubmit="return validateForm();">
  <div class="dropdown">
    <input id="itemsInput" type="text" name="myCountry">
  </div>
  <div class="dropdown">
    <input id="choicesInput" type="text" name="myCountry">
  </div>  
  <input type="submit" value="Submit">
</form>

CSS

.dropdown {
  position: relative;
  float: left;
  margin-right: 15px;
}

#itemsInput, #choicesInput {
 width: 100px;
}

.arrow {
  display: block;
  height: 19px;
  width: 28px;
  position: absolute;
  right: 1px;
  top: 1px;
  bottom: 1px;
  background: #f0f0f0;
  border-left: 1px solid #d3d3d3;
  cursor: pointer;
}

.arrow:after {
  content: "";
  position: absolute;
  right: 9px;
  top: 8px;
  border-top: 6px solid;
  border-right: 5px solid transparent;
  border-left: 5px solid transparent;
  border-color: #333333 transparent transparent transparent;
}

.invalid {
  border-color: red;
}

JavaScript

function dropdown(inp, arr) {
  var currentFocus;
  var parent = inp.parentNode;

  if (parent.classList.contains('dropdown')) {
    dropdown_arrow = document.createElement("div");
    dropdown_arrow.setAttribute("class", "arrow");
    parent.appendChild(dropdown_arrow);
  }

  dropdown_arrow.addEventListener("click", function(e) {
    closeAllLists();
    a = document.createElement("div");
    a.setAttribute("id", inp.id + "dropdown-list");
    a.setAttribute("class", inp.id + "dropdown-items");
    inp.parentNode.appendChild(a);
    for (i = 0; i < arr.length; i++) {
      b = document.createElement("div");
      b.innerHTML += arr[i];
      b.addEventListener("mouseover", function(e) {
        inp.value = this.textContent;
        programInputValue = inp.value;
      });         
      b.addEventListener("click", function(e) {
        inp.value = this.textContent;
        programInputValue = inp.value;
        closeAllLists();
      });      
      a.appendChild(b);
    }
  });

  function closeAllLists(elmnt) {
    var x = document.getElementsByClassName(inp.id + "dropdown-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
        x[i].parentNode.removeChild(x[i]);
      }
    }
  }

  document.addEventListener("click", function (e) {
    if (e.target.className != dropdown_arrow.className) {
      closeAllLists(e.target);
    }
  });
}

var items = ["Вариант 1","Вариант 2","Вариант 3","Вариант 4"];
dropdown(document.getElementById("itemsInput"), items);

var choices = ["Вариант 1","Вариант 2","Вариант 3","Вариант 4"];
dropdown(document.getElementById("choicesInput"), choices);

/*валидация*/
function validateForm() {
	event.preventDefault();
  var form, y, i, valid = true;
  form = document.getElementById("form");
  y = form.querySelectorAll("input");
  for (i = 0; i < y.length; i++) {

    if (y[i].value === "") {
      if (!y[i].closest('.hidden')) {
        y[i].classList.add("invalid");
        valid = false;
    ...