Wednesday 30 May 2012

Populate second select box according to the value selected in the first select box

You have come across many webpages where when you select your country its states automatically loads in the preceding combo box. Today, I am gonna show you how to do this with simple jQuery.



your HTML for the "form" would like this..

<form action="" method="post">
    <select name="drop_1" id="drop_1">
      <option value="">Select a Category</option>
      <option value="A">A</option>

      <option value="B">B</option>
      <option value="C">C</option>
    </select>
  
    <span id="wait_1" style="display: none;">
           <img alt="Please Wait" src="ajax-loader.gif"/>
    </span>

<span id="result_1" style="display: none;"></span>
</form>



your jQuery would like this....

$(document).ready(function() {
    $('#wait_1').hide();
    $('#drop_1').change(function(){
      $('#wait_1').show();
      $('#result_1').hide();
      $.get("func.php", {
        func: "drop_1",
        drop_var: $('#drop_1').val()
      }, function(response){
        $('#result_1').fadeOut();
        setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400);
      });
        return false;
    });
});

function finishAjax(id, response) {
  $('#wait_1').hide();
  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn();
}

and your PHP would like this......

if($_GET['func'] == "drop_1" && isset($_GET['func'])) {
   drop_1($_GET['drop_var']);
}

function drop_1($drop_var)
{
    include_once('db.php');
    $result = mysql_query("SELECT * FROM two_drops WHERE tier_one='$drop_var'")
    or die(mysql_error());
 
    echo '<select name="tier_two" id="tier_two">
          <option value=" " disabled="disabled" selected="selected">Choose one</option>';

           while($drop_2 = mysql_fetch_array( $result ))
            {
              echo '<option value="'.$drop_2['tier_two'].'">'.$drop_2['tier_two'].'</option>';
            }
 
    echo '</select> ';
}

You can simply rename the items that I use like names of pages, database, tables and fields with your ones and have a look...

Good Luck with your Learning ... :)

No comments:

Post a Comment