[英]Populate a third dropdown list based on two prior selected dropdown option
I'm currently working on three dependent dropdown lists that would be populated based on the user's selected option. 我目前正在研究三个依赖的下拉列表,这些列表将根据用户的选定选项进行填充。 For example, the first dropdown list has the options of "Apples, oranges, and banana" if the user chooses "apples", the second dropdown would be populated by different options based on that answer.
例如,如果用户选择“苹果”,则第一个下拉列表的选项为“苹果,橘子和香蕉”,第二个下拉列表将基于该答案由不同的选项填充。
My question is, I did this with the first two dropdowns basing on another question from stackoverflow. 我的问题是,我是根据stackoverflow的另一个问题来完成前两个下拉列表的。 How do I go about doing this with a third dropdown list that's based on the two prior dropdown options?
如何使用基于两个之前的下拉选项的第三个下拉列表执行此操作?
I would really appreciate someone's help, and if it's not too much to ask, help me understand the logic behind it. 我真的很感谢某人的帮助,如果要求不高,请帮助我了解其背后的逻辑。
<?php
$inquirytype = array();
$inquirytype[] = "Feedback";
$inquirytype[] = "Inquiry";
$inquirytype[] = "Requests";
$inquirytype[] = "Complaint";
$position = array();
$position['Inquiry'][] = "Product";
$position['Inquiry'][] = "Where to Buy";
$position['Inquiry'][] = "Apply";
$position['Inquiry'][] = "Others";
$position['Complaint'][] = "Product";
$position['Complaint'][] = "Services";
$position['Complaint'][] = "Personnel";
$position['Complaint'][] = "Others";
$position2 = array();
$position2['Product'][] = "Good";
$position2['Where to Buy'][] = "Okay";
$position2['Apply'][] = "Nice";
$position2['Others'][] = "There you go";
?>
<div class="home">
<form action="" method="POST">
<select id="inquirytype">
<?php foreach($inquirytype as $sa) { ?>
<option value="<?php echo $sa; ?>"><?php echo $sa; ?></option>
<?php } ?>
</select>
<p>
<select id="inquirytype2">
</select>
<p>
<select id="inquirytype3">
</select>
<p>
<button type="submit" name="submit">Submit</button>
</form>
</div>
<script type="text/javascript">
var s1 = document.getElementById("inquirytype");
var s2 = document.getElementById("inquirytype2");
onchange(); //Change options after page load
s1.onchange = onchange; // change options when s1 is changed
function onchange() {
<?php foreach ($inquirytype as $sa) {?>
if (s1.value == '<?php echo $sa; ?>') {
option_html = "";
<?php if (isset($position[$sa])) { ?> // Make sure position is exist
<?php foreach ($position[$sa] as $value) { ?>
option_html += "<option><?php echo $value; ?></option>";
<?php } ?>
<?php } ?>
s2.innerHTML = option_html;
}
<?php } ?>
}
</script>
Try to do this. 尝试这样做。 I added the same code for
inquirytype3
based on onchangeS2
like onchangeS2
based on onchange
我为基于
onchangeS2
inquirytype3
添加了相同的代码, inquirytype3
基于onchangeS2
的onchange
<script type="text/javascript">
var s1 = document.getElementById("inquirytype");
var s2 = document.getElementById("inquirytype2");
var s3 = document.getElementById("inquirytype3");
onchange(); //Change options after page load
s1.onchange = onchange; // change options when s1 is changed
s2.onchange = onchangeS2;
function onchange() {
<?php foreach ($inquirytype as $sa) {?>
if (s1.value == '<?php echo $sa; ?>') {
option_html = "";
<?php if (isset($position[$sa])) { ?> // Make sure position is exist
<?php foreach ($position[$sa] as $value) { ?>
option_html += "<option><?php echo $value; ?></option>";
<?php } ?>
<?php } ?>
s2.innerHTML = option_html;
}
<?php } ?>
}
function onchangeS2() {
<?php foreach ($position['Inquiry'] as $sa) {?>
if (s2.value == '<?php echo $sa; ?>') {
option_html = "";
<?php if (isset($position2[$sa])) { ?> // Make sure position is exist
<?php foreach ($position2[$sa] as $value) { ?>
option_html += "<option><?php echo $value; ?></option>";
<?php } ?>
<?php } ?>
s3.innerHTML = option_html;
}
<?php } ?>
}
</script>
I had a little play and put together a simple demo using ajax that binds all select menus to use a single event handler function. 我玩了一点,然后使用ajax编写了一个简单的演示,该演示将所有选择菜单绑定在一起以使用单个事件处理函数。 The event handler listens for
onchange
events and sends an ajax request to the designated PHP script - in this case it is the same page but could easily be a separate script/page. 事件处理程序侦听
onchange
事件,并将ajax请求发送到指定的PHP脚本-在这种情况下,它是同一页面,但很容易是单独的脚本/页面。
The $payload
variable is based upon the various array variables you have above but has been restructured to facilitate a lookup mechanism in response to the ajax request. $payload
变量基于您上面具有的各种数组变量,但已进行了重组以方便响应ajax请求的查找机制。 There are comments throughout which should help. 贯穿其中的评论应该有所帮助。 You could copy all of the above and create a new document, save and run to test.
您可以复制以上所有内容并创建一个新文档,保存并运行以进行测试。 Hope it will help!
希望对您有所帮助!
<?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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.