Marcelo Rojas Marcelo Rojas - 25 days ago 6
Javascript Question

Editable select and auto complete javascript

I need help, I have a select in my jsp and I need that the element be editable and you can write to the select for find the value in the select. How could I do this with js or jQuery?
My select take the values from the MySQL.

<div class="col-md-2">Descripcion:</div>
<div class="col-md-3">
<select title="0" contenteditable="true" class="form-control cbDescripcion"></select>
</div>

Answer
  • You can't set contenteditable into <select>.
  • There are multiple jQuery's plugins like select2 to make select list searchable witch override your static select list with advanced options like Ajax.

  • Below is an example for searchable dropdown menu. Also with ajax call.

$("#search").on("keyup", function() {
  //to call ajax
  //remoteSearch();
  //or static search
  var v = this.value.replace(/\s+/g, " ").trim().toLowerCase();
  if (v == "") return $(".option").hide();
  $(".option").hide();
  $(".option").each(function() {
    var t = $(this).text().toLowerCase();
    if (t.indexOf(v) > -1) $(this).show();
  });
});

$(document).on("click", ".option", function() {
  $("#search").val($(this).text());
  $(".option").hide();
});

function remoteSearch() {
  $.ajax({
    url: "data.php",
    data: {
      "search": $("#search").val() //search box value
    },
    dataType: "json", // recommended response type
    success: function(data) {
      //data = ["name1","name2","name3"];
      $(".options").html(""); //remove list
      $.each(data, function(i, v) {
        $(".options").append("<li class='option'>" + v + "</li>");
      });
    },
    error: function() {
      alert("can't connect to db");
    }
  });
}
#search {
  padding: 5px;
}
#select-containe {
  width: 200px;
}
.option {
  padding: 5px;
  display: none;
  color: white;
  background: orange;
  cursor: hand;
}
.option:hover {
  color: orange;
  background: white;
}
.options {
  height: 100px;
  width: 190px;
  overflow: auto;
  padding: 0;
  margin: 0;
  display: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='select-container'>
  <input id='search' placeholder='search names' />
  <ul class='options'>
    <li class='option'>Mohamed</li>
    <li class='option'>Ahmed</li>
    <li class='option'>Mahmoud</li>
    <li class='option'>Mustafa</li>
    <li class='option'>mohamed</li>
    <li class='option'>ahmed</li>
    <li class='option'>mahmoud</li>
    <li class='option'>mustafa</li>
  </ul>
</div>
choose names from above list

Comments