Dynamic Selection Box

In this tutorial I will show you a how to create a Dynamic Selection Box. This project or the dynamic selection box is compose of country, state, and city using the dropdown function. This project will implement a relational dropdown of country, state, and city using jQuery, Ajax, PHP, MySQL and Bootstrap. And it means that state is related with country and the city is related with the state. Based on changing of country & state, respective state & city will be fetched from the database without reloading the page using jQuery, Ajax, PHP, MySQL and Bootstrap.

Sample Code

Database Configuration this script helps to connect and select the correspond database.
  1. <?php
  2. $dbhost = 'localhost';
  3. $dbusername = 'root';
  4. $dbpassword = '';
  5. $dbname = 'dynamic';
  6. $db = new mysqli($dbhost, $dbusername, $dbpassword, $dbname);
  7.  
  8. if ($db->connect_error) {
  9. die("Connection failed: " . $db->connect_error);
  10. }
  11. ?>
The Javascript for pulling the data in the database.
  1. $(document).ready(function(){
  2. $('#country').on('change',function(){
  3. var countryID = $(this).val();
  4. if(countryID){
  5. $.ajax({
  6. type:'POST',
  7. url:'ajaxData.php',
  8. data:'country_id='+countryID,
  9. success:function(html){
  10. $('#state').html(html);
  11. $('#city').html('<option value="">Select Your State First</option>');
  12. }
  13. });
  14. }else{
  15. $('#state').html('<option value="">Select Your Country First</option>');
  16. $('#city').html('<option value="">Select Your State First</option>');
  17. }
  18. });
  19. $('#state').on('change',function(){
  20. var stateID = $(this).val();
  21. if(stateID){
  22. $.ajax({
  23. type:'POST',
  24. url:'ajaxData.php',
  25. data:'state_id='+stateID,
  26. success:function(html){
  27. $('#city').html(html);
  28. }
  29. });
  30. }else{
  31. $('#city').html('<option value="">Select Your State First</option>');
  32. }
  33. });
  34. });
result And if you already done or complete the project all you have to do is test it so you can know if their's an error. Hope that you learn in this project and enjoy coding. Don't forget to LIKE & SHARE this website.

Comments

Submitted byFranSet (not verified)on Thu, 03/16/2023 - 19:13

Hi and thank you for your tutorial, I tried it and it also worked for me. But I have a question. Is it possible to just give back the third information in an textbox? Like you have product categories, the product and one specific price for each. So you use the first dropdown for choosind the category, than the second dropdown choosing the product and then the price textbox should be filled automatically from the price in the db. I tried it with input type="text", but I am getting nowhere. Can you help me out? Thanks in advance.

Add new comment