This http://af-design.com/blog/2010/05/12/using-jquery-uis-autocomplete-to-populate-a-form/ script automatically fills state and zip, based on city.
There is one row with id like id="city". If I want additional rows, I must use something like id="city1", id="city2" etc.
In javascript code then may use something like
$("#city").val(ui.item.city);
$("#city1").val(ui.item.city1);
This is not ok, if I have many rows.
So I trying to change. Below is changed code
$(document).ready(function(){
var ac_config = {
source: "__demo_cities.php",
select: function(event, ui){
$('[id^="city"]').val(ui.item.city);
$('[id^="state"]').val(ui.item.state);
$('[id^="zip"]').val(ui.item.zip);
},
minLength:1
};
$('[id^="city"]').autocomplete(ac_config);
});
HTML
<input type="text" name="city[]" id="city" value="" />
<input type="text" name="state[]" id="state" value="" />
<input type="text" name="zip[]" id="zip" value="" />
<br>
<input type="text" name="city[]" id="city1" value="" />
<input type="text" name="state[]" id="state1" value="" />
<input type="text" name="zip[]" id="zip1" value="" />
If I enter something in city
script automatically fills id="state"
, id="zip"
(that is ok), but it also automatically fills id="city1"
, id="state1"
and id="zip1"
(that is not necessary).
Need behavior: if enter something in id="city"
, automatically fills only id="state"
and id="zip"
and all other fields remains blank/unchanged; if enter in id="city1"
, automatically fills only id="state"
and id="zip"
and all other fields remains blank/unchanged.
Based on @JNF advice there is one code that works
$(document).ready(function(){
var ac_config = {
source: "__demo_cities.php",
select: function(event, ui){
$(this).closest(".myForm").find('[id^="city"]').val(ui.item.city);
$(this).closest(".myForm").find('[id^="state"]').val(ui.item.state);
$(this).closest(".myForm").find('[id^="zip"]').val(ui.item.zip);
},
minLength:1
};
$('[id^="city"]').autocomplete(ac_config);
});