Skip to content

Instantly share code, notes, and snippets.

@johnnncodes
Created January 29, 2014 08:29
Show Gist options
  • Save johnnncodes/8683891 to your computer and use it in GitHub Desktop.
Save johnnncodes/8683891 to your computer and use it in GitHub Desktop.
Cities auto complete separated by commas using jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/flick/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<style type="text/css">
.ui-menu .ui-menu-item a,.ui-menu .ui-menu-item a.ui-state-hover, .ui-menu .ui-menu-item a.ui-state-active {
font-weight: normal;
margin: -1px;
text-align:left;
font-size:14px;
}
.ui-autocomplete-loading { background: white url("/images/ui-anim_basic_16x16.gif") right center no-repeat; }
</style>
<script type="text/javascript">
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
jQuery(function () {
jQuery("#f_elem_city").autocomplete({
source: function (request, response) {
jQuery.getJSON(
"http://gd.geobytes.com/AutoCompleteCity?callback=?&q=" + extractLast( request.term ),
function (data) {
response(data);
}
);
},
minLength: 3,
select: function (event, ui) {
var selectedObj = ui.item;
//j Query("#f_elem_city").val(selectedObj.value);
getcitydetails(selectedObj.value);
return false;
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
jQuery("#f_elem_city").autocomplete("option", "delay", 100);
});
</script>
<form action="" method="post" name="form_demo" id="form_demo" enctype="multipart/form-data" onsubmit="return false;">
<p><b>Please enter</b> your city here to see it work. <input class="ff_elem" type="text" name="ff_nm_from[]" value="" id="f_elem_city"/>
</form>
<script type="text/javascript">
function getcitydetails(fqcn) {
if (typeof fqcn == "undefined") fqcn = jQuery("#f_elem_city").val();
cityfqcn = fqcn;
if (cityfqcn) {
jQuery.getJSON(
"http://gd.geobytes.com/GetCityDetails?callback=?&fqcn="+cityfqcn,
function (data) {
var terms = split( jQuery("#f_elem_city").val() );
// remove the current input
terms.pop();
// add the selected item
terms.push( data.geobytescity );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
jQuery("#f_elem_city").val(terms.join( ", " ));
return false;
}
);
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment