How To Create Autocomplete In TextBox Using PHP

If you are looking for a source code on How To Create Autocomplete In TextBox Using PHP then you are at the right place. This tutorial can provide you an auto-suggestion or autocomplete in the textbox for all users while you typing in the textbox. In this case, we are going to suggest the Province of the Philippines from the database that starts with the keyword typing by the user. TextBox Field - HTML This source code contains textbox, and this is for autocomplete function.
  1. <div class="container_search">
  2. <h2 style="color:white;" class="blink_text">
  3. Province Of The Philippines
  4. </h2>
  5. <input type="text" id="search_textBox" autofocus="autofocus" />
  6. <div id="suggestion_list"></div>
  7. </div>
Autocomplete Script - jQuery This script will help us to do the function of autocomplete.
  1. <script src="js/code_js.js" type="text/javascript"></script>
  2.  
  3. <script>
  4. $(document).ready(function(){
  5. $("#search_textBox").keyup(function(){
  6. $.ajax({
  7. type: "POST",
  8. url: "list_of_province.php",
  9. data:'keyword='+$(this).val(),
  10. beforeSend: function(){
  11. $("#search_textBox").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px");
  12. },
  13. success: function(data){
  14. $("#suggestion_list").show();
  15. $("#suggestion_list").html(data);
  16. $("#search_textBox").css("background","#FFF");
  17. }
  18. });
  19. });
  20. });
  21.  
  22. function selectCountry(val) {
  23. $("#search_textBox").val(val);
  24. $("#suggestion_list").hide();
  25. }
  26. </script>
Database Using PHP This is our PHP Script for our database.
  1. <?php
  2. require_once("db.php");
  3. $db_handle = new DB();
  4. if(!empty($_POST["keyword"])) {
  5. $query ="SELECT * FROM province WHERE province_name like '" . $_POST["keyword"] . "%' ORDER BY province_name LIMIT 0,6";
  6. $result = $db_handle->runQuery($query);
  7. if(!empty($result)) {
  8. ?>
  9. <ul id="province_list">
  10. <?php
  11. foreach($result as $country) {
  12. ?>
  13. <li onClick="selectCountry('<?php echo $country["province_name"]; ?>');"><?php echo $country["province_name"]; ?></li>
  14. <?php } ?>
  15. </ul>
  16. <?php } } ?>
And, this is the output. Result Share us your thoughts and comments below. Thank you so much for dropping by and reading this tutorial post. For more updates, don’t hesitate and feel free to visit this website more often and please share this with your friends or email me at [email protected]. Practice Coding. Thank you very much.

Add new comment