JSFiddle - React, Tailwind, and code Playground

by pierian_design

HTML

<form id="form">
  <div class="dropdown">
    <input id="itemsInput" type="text" name="myCountry">
  </div>
  <div class="dropdown">
    <input id="choicesInput" type="text" name="myCountry">
  </div>  
  <input id="button" type="button" value="Submit">
</form>

CSS

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

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

.arrow {
  display: block;
  height: 17px;
  width: 28px;
  position: absolute;
  right: 2px;
  top: 2px;
  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 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("click", function(e) {
        inp.value = this.textContent;
        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);


/*валидация*/
document.forms[0].addEventListener("input", function(e) {
	var t = e.target.closest('input');
	if(!t) return;
  
      if (t.value.trim() != "") {
        t.classList.remove("invalid");
      } else {
        t.classList.add("invalid");
      } 
    });