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

后端 未结 1 349
悲哀的现实
悲哀的现实 2020-12-22 03:23

i have two the 1st one say country

country_id          country _name
1                   India
2                   Australia
3                   Netherlands
         


        
相关标签:
1条回答
  • 2020-12-22 03:48

    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  '';
        }
    }
    
    0 讨论(0)
提交回复
热议问题