I want to add different autocompletes for different inputs. For example I have the following two input fields:
<input type="text" id="firstname" name="firstname" placeholder="Max" required />
<input type="text" id="lastname" name="lastname" placeholder="Mustermann" required />
So I currently add different autocompletes as follows:
$( document ).ready(function() {
$( '#firstname' ).autocomplete({
source: 'autocomplete_firstname.php',
minLength: 1
});
$( '#lastname' ).autocomplete({
source: 'autocomplete_lastname.php',
minLength: 1
});
});
That works fine for me, but maybe is there a better way like a parameter? So that I can use only one class on autocomplete fields and only one .php-file which return the same result?
try this:
$( document ).ready(function() {
var focused_inp;
$( '#firstname,#lastname' ).on('focus',function(){ focused_inp = $(this).prop('name');}).autocomplete({
source: function(req, res){
$.ajax({
url: "autocomplete.php",
dataType: "jsonp",
data: {action: focused_inp, data: request.term },
success: function(result) { res(result) }
}) },
minLength: 1,
});
});
If you want to decouple your autocomplete instantiation code from the input markup, you can set your autocomplete source as a data attribute.
<input type="text" data-source="foo.php"/>
<input type="text" data-source="bar.php"/>
Then, in the create event, you can look for this attribute and set it as the source. This code is now applicable in many places, since you don't have to pass the source option directly when the widget is being created:
$('input').autocomplete({
minLength: 1,
create: function() {
var $this = $(this),
source = $this.data('source');
if (source) {
$this.autocomplete('option', 'source', source);
}
}
});
$('input').first().autocomplete('option', 'source');
// → 'foo.php'
$('input').last().autocomplete('option', 'source');
// → 'bar.php'