• support@answerspoint.com

jQuery AJAX Autocomplete – Country

2716

I want to auto complete textbox after key up dropdown country using jquery

1Answer


0

Autocomplete feature is used to provide auto suggestion for users while entering input. In this tutorial, we are going to suggest country names for the users based on the keyword they entered into the input field by using jQuery AJAX.

We have jQuery script to call AJAX request on key-up event. This request will read country names from database that starts with the keyword entered by the user.

Input Field with Autocomplete Feature

This HTML code contains text input field for auto suggesting country name to the user. On key-up from this input field the jQuery function is triggered.

<div class="frmSearch">
	<input type="text" id="search-box" placeholder="Country Name" />
	<div id="suggesstion-box"></div>
</div>

jQuery Autocomplete Script

This script sends user input to a PHP page via jQuery AJAX function. On success, the list of countries will be shown to the user. We can select country name for the input field from the auto-sugessted list.

// AJAX call for autocomplete 
$(document).ready(function(){
	$("#search-box").keyup(function(){
		$.ajax({
		type: "POST",
		url: "readCountry.php",
		data:'keyword='+$(this).val(),
		beforeSend: function(){
			$("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px");
		},
		success: function(data){
			$("#suggesstion-box").show();
			$("#suggesstion-box").html(data);
			$("#search-box").css("background","#FFF");
		}
		});
	});
});
//To select country name
function selectCountry(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}

Reading Country Names from Database using PHP

This PHP script fetches data from the country table and form HTML to be returned as auto suggesstion.

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["keyword"])) {
$query ="SELECT * FROM country WHERE country_name like '" . $_POST["keyword"] . "%' ORDER BY country_name LIMIT 0,6";
$result = $db_handle->runQuery($query);
if(!empty($result)) {
?>
<ul id="country-list">
<?php
foreach($result as $country) {
?>
<li onClick="selectCountry('<?php echo $country["country_name"]; ?>');"><?php echo $country["country_name"]; ?></li>
<?php } ?>
</ul>
<?php } } ?>

 

  • answered 8 years ago
  • B Butts

Your Answer

    Facebook Share        
       
  • asked 8 years ago
  • viewed 2716 times
  • active 8 years ago

Best Rated Questions