使用动态添加的元素在jQuery中自动完成
我的要求是当用户在一个输入字段中输入一些字符(最少3个)时可能会显示很少的选项,这也可能是动态添加的。
我无法在页面加载时加载数据,因为数据很大。 有一个ajax调用来获取过滤后的数据。
我得到的问题是在第2行的页面加载时出现Expected identifier
错误。那么,您能否告诉我们下面的代码有什么问题?
$(document).on('keydown.autocomplete', 'input.searchInput', function() { source: function (request, response) { // Line # 2 var id = this.element[0].id; var val = $("#"+id).val(); $.ajax({ type : 'Get', url: 'getNames.html?name=' + val, success: function(data) { var id = $(this).attr('id'); $(this).removeClass('ui-autocomplete-loading'); response(data); },error: function(data) { $('#'+id).removeClass('ui-autocomplete-loading'); } }); }, minLength: 3 });
如何使用其他方法:在创建输入时初始化自动完成:
$(function() { // settings for each autocomplete var autocompleteOptions = { minLength: 3, source: function(request, response) { $.ajax({ type: "GET", url: "getNames.html", data: { name: request.term }, success: function(data) { response(data); } }); } }; // dynamically create an input and initialize autocomplete on it function addInput() { var $input = $("", { name: "search", "class": "searchInput", maxlength: "20" }); $input .appendTo("form#myForm") .focus() .autocomplete(autocompleteOptions); }; // initialize autocomplete on first input $("input.searchInput").autocomplete(autocompleteOptions); $("input#addButton").click(addInput); });
jsFiddle与AJAX
试试这个。
$("#autocompleteElement").autocomplete({ source:function (data, response) { $ajax({ url:'your/url?name='+data.term, success:function(data){ response(data); } }) } });
此代码基于jquery UI自动完成。
我在下面的代码中添加新输入字段的方法。
function addInput(){ // Code to append new input filed next to existing one. $("table").find('input[id=clientId]:last').autocomplete({ source: function (request, response) { var id = this.element[0].id; var val = $("#"+id).val(); $.ajax({ type : 'Get', url: 'getName.html?name=' + val, success: function(data) { var id = $(this).attr('id'); $(this).removeClass('ui-autocomplete-loading'); response(data); }, error: function(data) { $('#'+id).removeClass('ui-autocomplete-loading'); } }); }, minLength: 3 }); }
还有一些在其他js中用于代码下面的所有其他(静态)输入字段的地方。
jQuery("input.searchInput").autocomplete({ source: function (request, response) { var id = this.element[0].id; var val = $("#"+id).val(); $.ajax({ type : 'Get', url: 'getName.html?name=' + val, success: function(data) { var id = $(this).attr('id'); $(this).removeClass('ui-autocomplete-loading'); response(data); }, error: function(data) { $('#'+id).removeClass('ui-autocomplete-loading'); } }); }, minLength: 3 });
注意: – 对于动态添加的输入字段中的任何自动完成请求,将调用addInput()函数的AutoComplete代码。
感谢@Salman和这篇文章在动态创建的输入字段上启用jQuery自动完成function,以便给我一个想法。