Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

php - How can i populate a dropdown list by selecting the value from another dropdown list

i have two the 1st one say country

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

where country_id in the first table is the country in the second table So 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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>

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  '';
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...