I am new to jQuery but have had good results so far.
Now I’m trying to define multiple autocomplete statements that will be associated with multiple text input fields.
I have manually created these 2, and they work fine:
$( "#fromLocation_1" ).autocomplete({
source: strLocations
});
$( "#fromLocation_2" ).autocomplete({
source: strLocations
});
However, this is not working:
$for(i=0; i<20; i++)
{
$( "#toLocation_"+i ).autocomplete({
source: strLocations
});}
So, either I’m taking a completely dumb approach or there’s some basic error in my code.
All help appreciated!
4
Answers
The issue with your loop for the autocomplete functionality seems to be a syntax error. In jQuery, the correct syntax for a for loop does not include a dollar sign ($) before for.
Here is the corrected version of your loop:
there seems to be a problem with the syntax, try it.
To create a loop in a jQuery function definition for setting up multiple autocomplete fields, you can use a standard JavaScript
for
loop. Your attempt is almost correct, but there are a couple of syntax errors. Here is how you can correctly define the loopExplanation:
for
loop: Ensure the for loop syntax is correct with proper parentheses and braces.i
usingvar
,let
, orconst
.i
.a) Since
source
is the same for both autocomplete, you can merge them into one:Working snippet:
b) Better approach: in case of the same source, add the same class to all autocomplete input and do it in one go like this:
Working snippet:
c) Don’t go for the loop way. It is not recommended at all.