Currently, I am experimenting with adding jQuery autocomplete functionality to all input boxes on a web page. Initially, there are only two input boxes, but users can dynamically add more. The autocomplete feature works fine in the first two boxes but fails in the dynamically added ones.
You can check out the code in action here: http://jsfiddle.net/HG2hP/
Here is the code snippet:
HTML:
<!doctype html>
<html>
<head>
<title>TakeMeHome</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<link type="text/css" rel="stylesheet" href="css/design.css"/>
</head>
<body>
<center>
Your Place:<input class="address" id="source" type="text"/><br/>
<div id= "div1">Friend1:<input class="address" id="friend1" type="text"/></div><br/>
<pre>
<div id="button">Add!</div> <div id="button2">Remove</div></br>
</pre>
<div id="sumbit_button">GO!</div>
<div id="map" style = "width: 500px; height: 500px"></div>
</center>
</body>
</html>
JavaScript (JS):
$(document).ready(function() {
var geocoder;
var map;
var marker;
var friends_cnt = 1;
var friends = [];
var distance = [];
$('#button').click(function() {
if (friends_cnt < 11) {
$('<div id = div' + (friends_cnt + 1) + '>Friend' + (friends_cnt + 1) + ':<input type="text" class="address" id="friend' + (friends_cnt + 1) + '"/></div>').insertAfter('#div' + friends_cnt);
friends_cnt++;
} else {
console.log("Limit reached");
}
});
// Code for removing buttons omitted for brevity
geocoder = new google.maps.Geocoder();
$(function() {
$(".address").autocomplete({
source : function(request, response) {
geocoder.geocode({
'address' : request.term
}, function(results, status) {
response($.map(results, function(item) {
return {
label : item.formatted_address,
value : item.formatted_address,
latitude : item.geometry.location.lat(),
longitude : item.geometry.location.lng()
}
}));
})
},
});
});
$('#sumbit_button').on("click", function() {
console.log("button clicked");
var a = [];
a.push($("#source").val());
for ( i = 1; i <= friends_cnt; i++) {
a.push($("#friend" + i).val());
}
// AJAX call and processing of response data omitted for brevity
});
CSS:
input {
margin: 10px 4px;
}
#button, #button2 {
width: 70%;
margin: 0 auto;
}
.ui-autocomplete {
background-color: white;
width: 300px;
border: 1px solid #cfcfcf;
list-style-type: none;
padding-left: 0px;
}
.ui-helper-hidden-accessible {
display: none;
}
If you spot any errors or have suggestions on how to improve the implementation of the autocomplete feature using classes, please let me know.