[jQuery] Autocomplete with dynamically generated input-fields
I take dates via ajax and create for every date 2 input fields. one
with the date an another empty input field.
On the empty field i want to add the autocomplete plugin/
functionality.
$(document).ready(function(){
$("#button").click(function(){
$.get("/test2.txt", function(text){ // a list with dates
var tokens = text.split('|');
var txt;
for (var i = 0; i < tokens.length; i++) {
txt = '';
var token = $.trim(tokens[i]);
txt += '<input type="text" name="testdate[]" value="'+token+'">';
txt += ' <input type="text" id="loc'+i+'"
name="testlocation[]" value="">';
txt += ' <input type="text" id="lochidden'+i+'"
name="testlocationid[]" value="">';
$("div.term").after(txt + '
');
// for every field, search.php returns one entry per row like 'title|
description|id'
$("#loc"+i).autocomplete("/search.php", {
delay: 150,
width: 260,
formatItem: formatItem,
formatResult: formatResult
});
// if selected one row of autocomplete
$("#loc"+i).result(function(event, data, formatted) {
$("#lochidden"+i).val(data[2]); // data[2] => id (is the
third part => title|description|id)
// alert(data[2]); works
});
}
});
});
function findValueCallback(event, data, formatted) {
$("<li>").text( !data ? "No match!" : "Selected: " +
formatted).appendTo("#result");
}
function formatItem(row) {
//var row = row.split("|");
return row[0] + " (" + row[1] + ")";
}
function formatResult(row) {
return row[0];
}
$("#locationX").autocomplete("/test2.txt", {
delay: 150,
width: 260,
formatItem: formatItem,
formatResult: formatResult,
selectFirst: false
});
});