【问题标题】:Autocomplete is not working for me using materialize使用实现自动完成对我不起作用
【发布时间】:2017-08-10 13:39:15
【问题描述】:

我想使用新的表单自动完成功能,我试过了,但没有打开下拉列表并建议搜索单词。 应该为 jquery $(input.autocomplete) 添加 class="autocomplete" .....而我的 jquery 代码是......

$("#productName").keyup(function (e) {
var min_length = 0;
var keyword = $('#productName').val();
$(function () {
if (keyword.length >= min_length) {
$.ajax({
url: "/getSearchedProductName",
type: 'POST',
datatype: 'JSON',
data: {
method: 'getSearchedProductName',
keyword: keyword
},
success: function (response) {
response = JSON.parse(response);
var projects = new Array();
var array = new Array();
var arr = new Array();
$.each(response.data, function (key, value) {
var projects = {
value1: value.product_name,
value2: value.image_url
};
array.push(projects);
});
$(function () {
$("#productName").autocomplete({
data: {
"Google": 'http://placehold.it/250x250',
"G1": 'http://placehold.it/250x250',
"G2": 'http://placehold.it/250x250',
"Go3": 'http://placehold.it/250x250',
"G4": 'http://placehold.it/250x250'
};

.autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>").append("<div class='autocomplete-content dropdown-  content' data-id=" + item.value + ">" + item.label + "</div>")
                                        .appendTo(ul);
};

if (e.which === 13) {
$.each(response.data, function (i, v) {
var prodID = v['product_id'];
if (prodID != null) {
window.location = webUrl + "/categorySearchItems?productId=" + prodID;
}
});
}
});
}
});
}
});
});

对于自动完成搜索,我使用了 cdn 脚本:

如果它适用于其他人,那么请告诉我如何让它适用于我。 如果有人有任何自动完成链接,请分享给我。

【问题讨论】:

  • 在 jsFiddle 上托管您的代码链接会很好,但这是我的 jsfiddle.net/LCv8L/1110
  • 它的工作,谢谢..

标签: javascript jquery jquery-ui autocomplete


【解决方案1】:

您的代码有一个小问题。正如您必须知道的,materialize 的自动完成功能适用于输入字段。 因此,您必须为 text-type-input 元素之一提供一个类,该元素位于类 input-field 的 div 中

$("#productName").autocomplete({
  data: {
    "Google": 'http://placehold.it/250x250',
    "G1": 'http://placehold.it/250x250',
    "G2": 'http://placehold.it/250x250',
    "Go3": 'http://placehold.it/250x250',
    "G4": 'http://placehold.it/250x250'
  };

我猜,代码应该是这样的 -

$('input.autocomplete').autocomplete({
  data: {
    "Google": 'http://placehold.it/250x250',
    "G1": 'http://placehold.it/250x250',
    "G2": 'http://placehold.it/250x250',
    "Go3": 'http://placehold.it/250x250',
    "G4": 'http://placehold.it/250x250'
  }
});

上面的代码定义了input元素的类autocomplete。 猜猜这会有所帮助。

【讨论】:

    猜你喜欢
    • 2013-04-05
    • 2017-01-07
    • 2014-01-17
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    相关资源
    最近更新 更多