PHP MYSQL dynamic select box

后端 未结 4 692
囚心锁ツ
囚心锁ツ 2021-01-16 12:14

I am trying to create a search box where the option selected from \'box1\' populates the options available for \'box2\'. The options for both boxes are given from my MYSQL d

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-16 12:23

    First create the no1 select menu with php as you mentioned above. Then add a 'change' eventListener to it like:

    $('#select1').change(createSelect2);
    
    function createSelect2(){
        var option = $(this).find(':selected').val(),
        dataString = "option="+option;
        if(option != '')
        {
            $.ajax({
                type     : 'GET',
                url      : 'http://www.mitilini-trans.gr/demo/test.php',
                data     : dataString,
                dataType : 'JSON',
                cache: false,
                success  : function(data) {            
                    var output = '';
    
                    $.each(data.data, function(i,s){
                        var newOption = s;
    
                        output += '';
                    });
    
                    $('#select2').empty().append(output);
                },
                error: function(){
                    console.log("Ajax failed");
                }
            }); 
        }
        else
        {
            console.log("You have to select at least sth");
        }
    }
    

    Now the no2 select menu has new options according to the select 1 selected option.

    And the php file:

     $data, 'error' => false);
    }
    else
    {
        $reply = array('error' => true);
    }
    
    $json = json_encode($reply);    
    echo $json; 
    ?>
    

    Of course there i use some demo data but you can make an sql query populate the $data array there and send them as json with the right headers. Finally use some more js for the second select menu:

    $('#select2').change(selectSelect2);
    
    function selectSelect2(){
        var option = $(this).find(':selected').val();
        if(option != '')
        {
            alert("You selected: "+option);
        }
        else
        {
            alert("You have to select at least sth");
        }
    }
    

    Check here http://jsfiddle.net/g3Yqq/2/ a working example

提交回复
热议问题