4 Flares Google+ 1 Facebook 3 Twitter 0 LinkedIn 0 4 Flares ×

Most of the websites and web-applications are developing in server scripting languages. And the GUI part are designed in jquery, css and html. For GUI designing purpose jquery is easy and light so that the website will open quickly.

We use jquery because it is the cross browser compatible, so that the GUI remain same in the modern browsers. Jquery also using to send back-end or to gathering the data from cross domain. In this example we use jquery for dynamic dependent select boxes so that the page will not refresh every time when the related data are loading.

In this post we are talking about the dynamic select box. And what we to do is first of all make a simple select box with some values. Lets say we want to make a student and subjects relation. And when we select the student the subject’s of that student will appear on the next select box.

Select Box HTML

<div class="container">
            <table width="100%" cellpadding="6" cellspacing="0" style="border-collapse:collapse;">
                <tr>
                    <td width="100"><label>Student Name: </label></td>
                    <td align="left">
                        <select name="sName" class="sel_box">
                            <option value="">Please Select</option>
                            <?php
                                $studentName = array(1=>'Jacob', 'Chris', 'John');
                                foreach( $studentName as $key=>$name ){
                                    echo "<option value='$key'>$name</option>";
                                }
                            ?>
                        </select> &nbsp;<span class="loader hide"><img src="ajax-loader.gif" alt="loader" title="loader"></span>
                    </td>
                </tr>
                <tr>
                    <td><label>Subjects: </label></td>
                    <td align="left">
                        <select name="sSubject" class="sel_box">
                            <option value="">Please Select</option>
                        </select>
                    </td>
                </tr>
            </table>
        </div>

As you see the above, the highlighted lines: 9-12, i simply take an array and put some students name into it, the key of the student’s array is starting from 1. And with the help of foreach() loop i have put these values into the select box. And the highlighted lines: 20-22 contains a blank select box. Because we have to put the selected Student’s Subjects dynamically with the use of ajax, But before applying the jQuery, we will beautify this HTML section with the help of CSS.

Dynamic Select box CSS

div.container{
    margin: 0 auto;
    width: 280px;
    border: 1px dashed #333333;
    padding: 10px;
}
label{
    font-family: Verdana;
    font-size: 12px;
    color: #333333;
}
.sel_box{
    border: 1px solid #666666;
    height: 25px;
    line-height: 25px;
    padding: 3px;
    border-radius: 2px;
    -moz-border-radius: 2px;
    -webkit-border-radius: 2px;
    -o-border-radius: 2px;
    -ms-border-radius: 2px;
    font-size: 12px;
    font-family: Verdana;
    color: #333333;
}
.hide{
    display: none;
}

Now lets move on the jQuery side. What we have to do is, we have to apply event on the select box with the help of jQuery. And the .change() event is helping us to achieve this. There is some more events on the jQuery site, which help us to achieve this.

Here is our jQuery Part

$(document).ready(function(){
        
        /* Action On Select Box Change */
        $('select[name="sName"]').change(function(){
            var data = $(this).val(); // Get Selected Value
            
            // Display Loader
            $('.loader').ajaxStart(function(){
                $(this).removeClass('hide');
            });
            $('.loader').ajaxComplete(function(){
                $(this).addClass('hide');
            });
            
            /* Send Ajax Request on Every 
             * Select Box Change Event
             */            
            $.ajax({
                url: 'getdata.php', 
                data: 'data=' + data, 
                dataType: 'json', 
                success: function(data){
                    var str = "<option value=''>Please Select</option>";
                    
                    $.each(data, function(i, items){
                       str += "<option value='"+items.id+"'>"+items.subject+"</option>";
                    });
                    
                    $('select[name="sSubject"]').html( str );
                }
            });
            
        });
        
    });

In the above jQuery codes, the highlighted section is the ajax request to the ‘getdata.php’ file, And this php file returns the JSON data, It is not mandatory that we just use the JSON data only, you can directly fetch the html also or xml format etc. To know more about the dataType of the ajax request just visit on the jquery site. Now come to the point, after getting this json data we have to set this json data into the second select box in which we have to show the subject’s of the Student. Now lets move on the out PHP file ‘getdata.php’ which return the data in json format.

// Get Data from Ajax Request
     $data = $_GET['data'];
     $collect = array(); // Blank Array
     
     $query = "select * from tbl_student where p_id='$data'";
     $result = mysql_query($query);
             
     $num = 1;
     while( $row = mysql_fetch_assoc($result) ){
         $collect[$num]['id'] = $row['id'];
         $collect[$num]['subject'] = $row['subject'];
             
         $num++;
     }
     
     // Return Value in JSON format
     echo json_encode($collect);

Now we have completed our all the steps, but one more this in the last PHP file ‘getdata.php’, don’t forget to make the database connection before applying this query and do the changes according to your table. Because in this ‘tbl_student’ i have the parent id of the student and the field is ‘p_id’ which i matched to get the relevant subjects for the student. Hope you all enjoying this article, i have updated my post with the demo also.

About the author

Jogesh Sharma Jogesh Sharma is a web developer and blogger who loves all the things design and the technology, He love all the things having to do with PHP, WordPress, Joomla, Magento, Durpal, Codeigniter, jQuery, HTML5 etc. He is the author of this blog. If you'd like to connect with him, head on over the Google+