如何通过从另一个下拉列表中选择值来填充下拉列表

如何通过从另一个下拉列表中选择值来填充下拉列表

本文介绍了如何通过从另一个下拉列表中选择值来填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个第一个说国家

country_id          country _name
1                   India
2                   Australia
3                   Netherlands

the 2nd table is states
state_id           country         state name
1                   2              abc
2                   2              xyz
3                   3              pqr
4                   1              lmn
5                   1              rst

其中 country_id 在第一个表中是第二个表中的国家
所以现在我想要两个下拉列表一个为国家,另一个为州。第二个下拉列表必须根据第一个下拉列表中的所选项目进行更改,只要未选择第一个下拉菜单中的项目,则必须禁用第二个下拉列表。

where country_id in the first table is the country in the second tableSo now i want two drop downs one for country and another for states. The Second drop down values must must change as per the selected item in the first drop down and the second drop down must be disabled as long as the items in the first drop down is not selected

推荐答案

执行下面给出的html作为

Do a html as given below for Make

<?php $sql = "SELECT * FROM country";
$result = mysql_query($sql);
?>
<select id="country" name='country' onchange="get_states();">
<option value=''>Select</option>
<?php while ($row = mysql_fetch_array($result)) {
    echo "<option value='" . $row['country_id'] . "'>" . $row['country_name'] . "</option>";}
?>
</select>
<div id="get_state"></div> // Sub will be appended here using ajax

编写一个ajax函数get_states();

Write a ajax function get_states();

<script type="text/javascript">
function get_states() { // Call to ajax function
    var country = $('#country').val();
    var dataString = "country="+country;
    $.ajax({
        type: "POST",
        url: "getstates.php", // Name of the php files
        data: dataString,
        success: function(html)
        {
            $("#get_state").html(html);
        }
    });
}
</script>

文件getstates.php - 将从以下文件中获取Sub,该文件将附加到div <如果($ _POST){
$ country = $ _POST ['country']; p>

File getstates.php - Will get sub from the below file which will be appended to the div

if ($_POST) {
    $country = $_POST['country'];
    if ($country != '') {
       $sql1 = "SELECT * FROM state WHERE country=" . $country;
       $result1 = mysql_query($sql1);
       echo "<select name='state'>";
       echo "<option value=''>Select</option>";
       while ($row = mysql_fetch_array($result1)) {
          echo "<option value='" . $row['state_id'] . "'>" . $row['state_name'] . "</option>";}
       echo "</select>";
    }
    else
    {
        echo  '';
    }
}

这篇关于如何通过从另一个下拉列表中选择值来填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 03:04