我目前正在处理三个依赖下拉列表,这些下拉列表将根据用户选择的选项进行填充。例如,如果用户选择"苹果",第一个下拉列表具有"苹果、橙子和香蕉"选项,第二个下拉列表将基于该答案由不同的选项填充。
我的问题是,我根据堆栈溢出的另一个问题对前两个下拉列表进行了此操作。如何使用基于前两个下拉列表选项的第三个下拉列表执行此操作?
我真的很感激某人的帮助,如果不是太多的要求,请帮助我理解其背后的逻辑。
<?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>
尝试这样做。我为基于onchangeS2
inquirytype3
添加了相同的代码,例如基于 onchange
的onchangeS2
<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>
我玩了一会儿,并使用 ajax 整理了一个简单的演示,该演示将所有选择菜单绑定为使用单个事件处理程序函数。事件处理程序侦听onchange
事件,并向指定的 PHP 脚本发送 ajax 请求 - 在这种情况下,它是同一页面,但很容易成为单独的脚本/页面。
$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>