可编辑选择并自动完成javascript

时间:2016-11-07 15:41:39

标签: javascript jquery jsp

我的jsp中有一个select,我需要元素可编辑,用户可以写入select来查找select中的值。

我怎么能用js或jQuery做到这一点?

我的选择从MySQL获取值。

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

1 个答案:

答案 0 :(得分:0)

  • 您无法将 if ( $("input").val().length > 0) { alert("X"); } 设置为contenteditable
  • 有许多jQuery的插件,如select2 选择列表 searchable 使用Ajax等高级选项覆盖您的静态选择列表。

  • 以下是可搜索下拉菜单的示例。还有ajax电话。

&#13;
&#13;
<select>
&#13;
$("#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");
    }
  });
}
&#13;
#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;
}
&#13;
&#13;
&#13;

相关问题