这是我添加行class='form-control mybur'
:
$("body").on("click", "#add_row_bur", function() {
$("#bur" + o).html("<td><input type='text' name='bur_account_code[]' placeholder='Account Code' class='form-control mybur' data-provide='typeahead' id='account_code" + o + "' required/><td>;
$("#tab_logic_bur").append('<tr id="bur' + (o + 1) + '"></tr>');
o++
});
$("body").on("click", "#delete_row_bur", function() {
if (o > 1) {
$("#bur" + (o - 1)).html("");
o--
}
});
我尝试在其上实现typeahead,但它不起作用。我尝试使用此答案(answer 1,answer 2),但仍然失败。
这是我的代码:
var objects = [];
var map = {};
$('input.mybur').typeahead({
source: function(query, process) {
$.ajax({
url: 'proc_php/get_account_code.php',
type: 'POST',
dataType: 'JSON',
async: true,
success: function(data) {
objects = [];
map = {};
$.each(data, function(i, object) {
map[object.description] = object;
objects.push(object.description);
});
process(objects);
}
});
},
updater: function(item) {
$('input.mybur').blur(function() {
$(this).val(map[item].code);
});
return item;
}
});
我删除了我尝试过的所有代码。同样,这将适用于预先创建的元素:
<input type="text" name='bur_account_code[]' placeholder='Account Code' class="form-control mybur" data-provide="typeahead" required/>
答案 0 :(得分:0)
问题在于动态添加的输入元素,您需要在创建插件后对其进行初始化。
所以一个解决方案是首先创建一个方法,可以重用它来为一组传递的元素初始化插件,比如
var objects = [];
var map = {};
function createTypeahead($els) {
$els.typeahead({
source: function (query, process) {
$.ajax({
url: 'proc_php/get_account_code.php',
type: 'POST',
dataType: 'JSON',
async: true,
success: function (data) {
objects = [];
map = {};
$.each(data, function (i, object) {
map[object.description] = object;
objects.push(object.description);
});
process(objects);
}
});
},
updater: function (item) {
$('input.mybur').blur(function () {
$(this).val(map[item].code);
});
return item;
}
});
}
//for the already present elements
createTypeahead($('input.mybur'));
然后在添加新元素代码
$("body").on("click", "#add_row_bur", function() {
var $td = $("<td><input type='text' name='bur_account_code[]' placeholder='Account Code' class='form-control mybur' data-provide='typeahead' id='account_code" + o + "' required/><td>")
$("#bur" + o).html($td);
$("#tab_logic_bur").append('<tr id="bur' + (o + 1) + '"></tr>');
o++
createTypeahead($td.find('input.mybur'));
});
$("body").on("click", "#delete_row_bur", function() {
if (o > 1) {
$("#bur" + (o - 1)).html("");
o--
}
});