Ashoka
Ashoka

Reputation: 480

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

Upvotes: 1

Views: 13797

Answers (1)

Saranya Sadhasivam
Saranya Sadhasivam

Reputation: 1294

Do a html as given below for Make

<?php $sql = "SELECT * FROM country";
$result = $pdo->query($sql);
?>
<select id="country" name='country' onchange="get_states();">
<option value=''>Select</option>
<?php foreach ($result as $row) {
    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 != '') {
        $sql = "SELECT * FROM state WHERE country=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$country]);
        echo "<select name='state'>";
        echo "<option value=''>Select</option>";
        foreach ($stmt as $row) {
            echo "<option value='" . $row['state_id'] . "'>" . $row['state_name'] . "</option>";
        }
        echo "</select>";
    } else {
        echo  '';
    }
}

Upvotes: 8

Related Questions