使用AJAX和jQuery自动选择下拉列表

问题描述:

I have 3 dropdown lists. 1) Type 2) Duration 3) Class

<select name="passenger_type_of_pass" class="pass">
    <option value="">- - Type - -</option>
    <?
       $result_type_of_pass = myquery($type_of_pass);                                           
       while($row = mysql_fetch_array($result_type_of_pass))
       {
          echo "<option value=\"" . $row['product_name'] . "\">" . $row['product_name'] . "</option>";  
       }
    ?>
</select>

<select name="passenger_duration" class="duration">
    <option>--Duration--</option>
</select>

<select name="passenger_class" class="class">
    <option>--Class--</option>
</select>

Using jQuery, I make them updated as there is change in each select box.

        $(".pass").change(function()
        {
            var pass=$(this).val();
            var dataString = 'pass='+ pass;

            $.ajax
            ({
                type: "GET",
                url: "duration.php",
                data: dataString,
                cache: false,
                success: function(html)
                {
                    $(".duration").html(html);
                }
            });

        });

        $(".duration").change(function()
        {
            var duration=$(this).val();
            var pass=$(".pass").val();
            var dataString = 'pass='+ pass + '&duration=' + duration;

            $.ajax
            ({
                type: "GET",
                url: "class.php",
                data: dataString,
                cache: false,
                success: function(html)
                {
                    $(".class").html(html);
                }
            });

        });

I want to change this code in such a way that as soon as I select "type_of_pass", the "duration" dropdown list gets populated and also the top option gets SELECTED!! With this auto-selected duration, jQuery for searching the class runs and gets populated with the top option selected.

Currently with my code, I have to CHANGE the duration to get the class populated.

Thanks

Trigger a change event after populate them like

$('.duration').change():

CODE:

$.ajax({
    type: "GET",
    url: "duration.php",
    data: dataString,
    cache: false,
    success: function(html) {
        $(".duration").html(html);
        $(".duration").change(); // here to trigger a change
    }
});

To set any specific options you can do

$('.duration option:eq(1)').prop('selected', true); // here I set the second option

DEMO