Dynamic drop down list using html and php

前端 未结 2 1498
北荒
北荒 2020-12-18 16:53

I\'m learning html and php, I have a mysql DB employees where there is a table called Employees_hired, which stores id, name, department and type of contract. I want to make

相关标签:
2条回答
  • 2020-12-18 17:38

    So you have the onchange in there and that's a start. The onchange is referencing a JavaScript function that you don't show. There are a couple quick ways to approach this:

    1. Post the form to itself (as you have chosen) or
    2. use ajax (possibly via jQuery for quickness).

    (both of these examples don't address how you are accessing the database)

    1)

    Using your run function:

    <script type="text/javascript">
         function run(){
              document.getElementById('form1').submit()
         }
    </script>
    

    Additional PHP:

    <?php
        if (isset($_POST['department']) && isset($_POST['type_hire']))
        {
            $value_of_department_list = $_POST['department'];
            $value_of_type_hire = $_POST['type_hire'];
    
            mysql_connect("localhost","root","");
            mysql_select_db("employees_hired");
            mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')");
    
            while($row_list=mysql_fetch_assoc($list))
            {
                echo  "<option value=\"{$row_list['name']}\">{$row_list['name']}</option>";
            }
        }
        else
        {
            echo  "<option>Please choose a department and a type of hire</option>";
        }
    ?>
    

    2)

    <script type="text/javascript">
         function run(){
              $.post('get_employees.php',$('form1').serialize(),function(data){
    
                   var html = '';
    
                   $.each(data.employees,function(k,emp){
                       $('select[name="employees"]').append($('<option>', {
                            value: emp.name,
                            text: emp.name
                        }));
                   .html(html);
              },"json");
         }
    </script>
    

    And get_employees.php would contain something like:

    <?php
    if (isset($_POST['department']) && isset($_POST['type_hire']))
    {
        $value_of_department_list = $_POST['department'];
        $value_of_type_hire = $_POST['type_hire'];
        $return = array();
    
        mysql_connect("localhost","root","");
        mysql_select_db("employees_hired");
        mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')");
    
        while($row_list=mysql_fetch_assoc($list))
        {
            $return[]['name'] = $row_list['name'];
        }
    
        echo json_encode($return);
    }
    ?>
    

    Note, these are just quickly written examples. A lot more could/should be done here.

    0 讨论(0)
  • 2020-12-18 17:40

    Heres a modified jQuery version of your code. (With some cleanup)

    <html>      
    <head>
         <title>Dynamic Drop Down List</title>
    </head>
    <body>
        <form id="form1" name="form1" method="post" action="<? $_SERVER['PHP_SELF']?>">
            department: 
            <select id="department" name="department" onchange="run()">  
                <!--Call run() function-->
                <option value="biology">biology</option>
                <option value="chemestry">chemestry</option>
                <option value="physic">physic</option>
                <option value="math">math</option>     
            </select><br><br>
            type_hire: 
            <select id="type_hire" name="type_hire" onchange="run()">  
                <!--Call run() function-->
                <option value="internal">Intenal</option>
                <option value="external">External</option>               
            </select><br><br>
            list of employees:
            <select name='employees'>
                <option value="">--- Select ---</option>
                <?php
                mysql_connect("localhost","root","");
                mysql_select_db("employees_hired");
                $list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
                while($row_list=mysql_fetch_assoc($list)){
                ?>
                <option value="<?php echo $row_list['name']; ?>">
                    <? if($row_list['name']==$select){ echo $row_list['name']; } ?>
                </option>
                <?php
                }
                ?>
            </select>
        </form> 
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <!--[ I'M GOING TO INCLUDE THE SCRIPT PART DOWN BELOW ]-->
    </body>
    </html>
    

    Now I cleaned up the tags, and added a hotlink to jQuery using googleapis free cdn. Next is the actual javascript. Btw. DO NOT USE THE MYSQL_* FUNCTIONS IN PHP. They are depreciated. Check out http://php.net/manual/en/mysqlinfo.library.choosing.php for more info on that. On to the scripting...

    <script type="text/javascript">
    $('#type_hire').change(function() {
       var selected = $('#type_hire option:selected');  //This should be the selected object
       $.get('DropdownRetrievalScript.php', { 'option': selected.val() }, function(data) {
          //Now data is the results from the DropdownRetrievalScript.php
          $('select[name="employees"]').html(data);
       }
    }
    </script>
    

    Now I just freehanded that. But I'll try and walk you though it. First we grab the "select" tag that we want to watch (the hashtag means find the element by ID). Then we grab the selected option within that. Next we run a AJAX call to preform a GET on the page "DropdownRetrievalScript.php" which you would create. What that script should do is take the GET variable "option" and run it through the database. Then have it echo out the "option" tags. Our javascript stuff then takes those results and plugs them directly into the select tag with the name attribute of employees.

    Remember that AJAX is just like inputing that url into your browser. So the data variable is literally whatever code or text that url would display. It can be Text, HTML, JSON, XML, anything.

    0 讨论(0)
提交回复
热议问题