I use Jquery autocomplete to query a DB. The function is bound to all text fields with the class "completeme_accounts". That works fine for the default text field, which is present when the page loads. However, when I add more text fields via Jquery, autocomplete doesn't work on them. I've checked several similar solutions here, but I can't find a solution that works with my code. I'm guessing I need to use Jquery .on (since live is deprecated) but I don't know how. My code:
$(document).ready(function(){
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( ".completeme_accounts" ).autocomplete({
mustMatch: true,
source: "accounts_autocomplete.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
},
change: function (event, ui) {
if (!ui.item) {
$(this).val('');
}
}
});
});
}); // Doc ready
Table with input fields:
<table id="addaccount">
<tr>
<td><div class="ui-widget"><input name="account[1]" type="text" class="completeme_accounts" id="account1" value=""></div></td>
<td><input type="radio" name="source" id="radio" value="radio" class="required"></td>
</tr>
<tr>
<td colspan="2"><a href="#" id="addrow" onclick="return false;">Add another account</a></td>
</tr>
</table>
Script to append extra input fields:
<script>
$rowid = 1;
$("#addrow").on("click", function(){
$rowid = $rowid + 1;
$('#addaccount tr:last').before('<tr><td><div class="ui-widget"><input name="account['+$rowid+']" type="text" class="completeme_accounts" id="account'+$rowid+'" value=""></div></td><td><input type="radio" name="payment_source" id="radio" value="radio" class="required"></td></tr>');
});
</script>