根据先前选择的两个下拉选项填充第三个下拉列表

时间:2019-07-27 07:06:08

标签: javascript php html

我目前正在处理三个依赖的下拉列表,这些列表将根据用户的选择选项进行填充。例如,如果用户选择“苹果”,则第一个下拉列表的选项为“苹果,橘子和香蕉”,第二个下拉列表将根据该答案由不同的选项填充。

我的问题是,我是基于前两个下拉列表基于stackoverflow的另一个问题进行此操作的。我该如何使用基于前两个下拉选项的第三个下拉列表来做到这一点?

我真的很感谢某人的帮助,如果要求不高,请帮助我理解其背后的逻辑。

select *,ID- 
(
SELECT ID
FROM
  (
    SELECT
      ID,amount,
      Maxamount =q.mymax
    FROM
      Table_4 
  ) AS derived
WHERE
  amount = Maxamount
) as result
from (

    SELECT ID, date,
    MAX(amount) 
    OVER (ORDER BY date ASC ROWS 5 PRECEDING) mymax
    FROM Table_4 
)as q

2 个答案:

答案 0 :(得分:0)

尝试执行此操作。我为基于inquirytype3的{​​{1}}添加了相同的代码,就像基于onchangeS2的{​​{1}}

onchangeS2

答案 1 :(得分:0)

我做了一点工作,并使用ajax编写了一个简单的演示,该演示将所有选择菜单绑定在一起以使用单个事件处理程序功能。事件处理程序侦听onchange事件,并将ajax请求发送到指定的PHP脚本-在这种情况下,它是同一页面,但很容易是单独的脚本/页面。

$payload变量基于您上面具有的各种数组变量,但已进行了重组以方便响应ajax请求的查找机制。贯穿其中的评论应该有所帮助。您可以复制以上所有内容并创建一个新文档,保存并运行以进行测试。希望对您有所帮助!

<?php

    $payload = (object)array(
        'Types'         =>  array(
            'Feedback',
            'Enquiry',
            'Complaints',
            'Request'
        ),
        /* The following keys appear in the Types array and are menu items in initial dropdown  */
        'Feedback'      =>  array(
            'Positive'      =>  array('a','b','c'),
            'Neutral'       =>  array('e','f','g'),
            'Negative'      =>  array('h','i','j')
        ),
        'Enquiry'       =>  array(
            'Product'       =>  array('apple','banana','cherry','date','elderberry'),
            'Where to Buy'  =>  array('online','in-store','mail order','Del Boys Emporium'),
            'Apply'         =>  array('Office staff','Retail staff','Managerial position','Fluffer'),
            'Other'         =>  array('Let us know')
        ),
        'Complaints'    =>  array(
            'Product'       =>  array('Faulty','Incomplete','Poor quality','Damaged'),
            'Services'      =>  array('Ineffectual','Low-Grade','Unsuitable'),
            'Personnel'     =>  array('Lazy','Rude','Smelly'),
            'Other'         =>  array('Let us know')
        ),
        'Request'       =>  array(
            'Improvement'   =>  array('Bigger knobs','Smaller knobs','Louder whistle','Brighter colours'),
            'Assistance'    =>  array('Technical Assistance','Repairs','Customer services','Physical and mental support')
        ),

        /* The following does NOT appear in the Types array so will not be a menu item in 1st dropdown */
        'Bogus'         =>  array(
            'foo'           =>  array('bar')
        )
    );





    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['value'] ) ){
        ob_clean();

        $action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
        $value=filter_input( INPUT_POST, 'value', FILTER_SANITIZE_STRING );


        if( $action && $value ){

            /* create 2nd select menu options */
            if( property_exists( $payload, $value ) ){
                echo '<option selected hidden disabled>Please select';
                foreach( $payload->$value as $key => $arr )printf( '<option>%s', ucwords( strtolower( $key ) ) );
            }

            /* create 3rd select menu options */
            if( array_key_exists( $value, $payload->$action ) ){
                echo '<option selected hidden disabled>Please select';
                foreach( $payload->$action[ $value ] as $key => $item )printf( '<option>%s', ucwords( strtolower( $item ) ) );
            }
        }
        exit();
    }
?>
<!doctype html>
<html>
    <head>
        <title>Chained SELECT menus using ajax</title>
        <script>
            const ajax=function(m,u,p,c,o){
                /*
                    m=Method,
                    u=Url,
                    p=Params,
                    c=Callback,
                    o=Options
                */
                const xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o );
                };
                let params=[];
                for( let n in p )params.push( n+'='+p[n] );

                switch( m.toLowerCase() ){
                    case 'post': p=params.join('&'); break;
                    case 'get': u+='?'+params.join('&'); p=null; break;
                }
                xhr.open( m.toUpperCase(), u, true );
                xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
                xhr.send( p );
            }


            /*
                Callback function to populate dependant menu
                and modify other DOM elements
            */
            const ajax_callback=function(r,o){
                /*
                    r=response
                    o=options ( sent by ajax function )
                */
                if( o.menu != null ){

                    if( o.action=='Types' ){
                        /* when first dropdown changes, other dropdowns are cleared and the submit button is disabled */
                        document.querySelectorAll('select:not([data-action="Types"])').forEach( sel=>{ sel.innerHTML=''; } )
                        o.bttn.disabled=true;
                    }

                    if( o.menu === o.bttn )o.bttn.disabled=false;
                    else {
                        o.menu.innerHTML=r;
                        o.menu.dataset.action=o.value;
                    }
                }
            }

            /*
                The event handler that is invoked by changing the value
                of the dropdown menus.
            */
            const evtchangehandler=function(e){
                let method='post';
                let url=location.href;
                let params={
                    'action':this.dataset.action,
                    'value':this.value
                };
                let opts={
                    value:this.value,
                    action:this.dataset.action,
                    menu:document.querySelector( '[name="'+this.dataset.dependant+'"]' ),   // the target SELECT to be populated
                    bttn:document.querySelector( 'input[type="submit"]' )                   // the submit button to be enabled if final select is changed
                };
                let args=[ method, url, params, ajax_callback, opts ];
                ajax.apply( this, args );
            }



            /*
                Bind ALL select menus that satisfy the selection criteria
                using querySelectorAll. jQuery has other methods available
                to do the same thing
            */
            document.addEventListener( 'DOMContentLoaded', function(){
                document.querySelectorAll( 'form[ name="interaction" ] select' ).forEach( sel=>{
                    sel.addEventListener('change', evtchangehandler )
                });             
            });
        </script>

        <style>
            select,
            [type='submit'] { padding:1rem; width:300px; margin:0.25rem; }
        </style>
    </head>
    <body>

        <form name='interaction' method='post'>
            <h1>Chained SELECT menus using ajax</h1>
            <!--

                initial dropdown is populated based upon
                the $payload->Types array

            -->
            <select name='menu-1' data-action='Types' data-dependant='menu-2'>
                <option selected hidden disabled>Please select initial type
                <?php
                    sort( $payload->Types );
                    foreach( $payload->Types as $type )printf('<option>%s', $type );
                ?>
            </select>
            <!--

                subsequent dependant select menus will be populated
                dynamically based upon selection made in previous
                menu

            -->
            <select name='menu-2' data-dependant='menu-3'></select>
            <select name='menu-3' data-dependant='bttn'></select>
            <!--

                Form submit button is disabled until items 
                from all select menus have been chosen

            -->
            <input name='bttn' type='submit' disabled />
            <?php
                if( $_SERVER['REQUEST_METHOD']=='POST' )printf( '<pre>%s</pre>', print_r( $_POST, true ) );
            ?>
        </form>
    </body>
</html>
相关问题