我有一个select option
基于另一个select option
。
含义, 如果从第一个选项中选择选项:一个,则第二个选项应包含选项: S1,F1 。
如果从第一个选项中选择选项:两个,则第二个选项应包含选项: S2,F2 。
依旧......
但我的第二 select option
拥有所有选项。
注意:select中的选项基于数据库。
我试过了:
<td><select class="country" name="item1">
<option value="Select Item">Item</option>
<?php
$stmt = $user_home->runQuery('SELECT * FROM item ORDER BY Sr ASC ');
$stmt->execute();
if($stmt->rowCount() > 0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
?>
<option value="<?php echo $IRN ?>"><?php echo $Name; ?></option>
<?php
}
}
?>
</select></td>
<td><select class="country" name="service1">
<option value="Select Service">Service</option>
<?php
$stmt = $user_home->runQuery('SELECT * FROM service WHERE IRN = :irn ORDER BY Sr ASC ');
$stmt->bindParam(':irn',$IRN);
$stmt->execute();
if($stmt->rowCount() > 0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
?>
<option value="<?php echo $SRN ?>"><?php echo $Name; ?></option>
<?php
}
}
?>
</select></td>
重点代码:
$stmt = $user_home->runQuery('SELECT * FROM service WHERE IRN = :irn ORDER BY Sr ASC ');
$stmt->bindParam(':irn',$IRN);
$stmt->execute();
我知道如何使用固定值(不使用数据库和编码所有选项)来执行此操作,但我无法使用动态值(使用数据库作为选项)。
答案 0 :(得分:0)
下面的简单链式选择菜单示例应该让你了解如何实现目标 - 你需要研究这个并实现数据库调用,但测试你可以复制整段代码,保存到
<?php
/*
Include other PHP files/libraries,
set the session etc etc
.....
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
ob_clean();
$action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
$id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );
if( $action && $id && !is_nan( $id ) ){
/*
In production you would use the supplied POST values to query the database
and process the recordset - sending back the results as formatted HTML to
the AJAX callback function.
For the sake of demonstration though the script simply sends back data from a
simple loop...
sql=select * from table where id=? etc
*/
for( $i=1; $i <= 10; $i++ )echo "<option value='Service-$id-$i'>Service-$id-$i";
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>Dependent / Chained SELECT menus</title>
<script type='text/javascript' charset='utf-8'>
/* Basic Ajax function */
function ajax(m,u,p,c,o){
/*
m=Method,
u=Url,
p=Params,
c=Callback,
o=Options
*/
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
};
var params=[];
for( var 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 second menu */
function createmenu(r,o,h){
/*
r=response
o=options ( sent by ajax function )
h=response headers
*/
o.menu.innerHTML=r;
}
function bindEvents(){
/* Get references to the two dropdown menus */
var oSelItem=document.querySelector('select[name="item1"]');
var oSelService=document.querySelector('select[name="service1"]');
/* Assign an `onchange` event listener */
oSelItem.onchange=function(e){
var method='post';
var url=location.href;
/* the parameters to send to the PHP script */
var params={
'action':'get_dependant_menu',
'id':this.options[ this.options.selectedIndex ].value
};
/* Options to pass to the ajax callback */
var opts={
menu:oSelService
};
/* make the ajax request */
ajax.call( this, method, url, params, createmenu, opts );
}.bind( oSelItem );
}
document.addEventListener( 'DOMContentLoaded', bindEvents,false );
</script>
<style type='text/css' charset='utf-8'>
select {padding:1rem;width:300px;}
</style>
</head>
<body>
<h1>Chained select menus using basic ajax</h1>
<form method='post'>
<select name='item1' class='country'>
<?php
/*
In production your code would use a database call
to populate the menu but for example purposes it
simply uses a loop
*/
for( $i=1; $i <= 10; $i++ )echo "<option value=$i>Item $i";
?>
</select>
<select name='service1' class='country'>
</select>
</form>
</body>
</html>
我不知道为什么你不能或不愿意尝试使用自己的数据库代码来实现上述AJAX解决方案,但是在坚持不懈的恳求之后,以下内容可能会给你一个更好的想法。这还没有经过测试!
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
ob_clean();
$action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
$id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
if( $action && $id && !empty( $id ) ){
$sql='select * from service where irn = :irn order by sr asc';
$stmt->bindParam(':irn',$id);
$stmt->execute();
if( $stmt->rowCount() > 0 ){
while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
echo "<option value='{$row['IRN']}'>{$row['Name']}";
}
}
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>Dependent / Chained SELECT menus</title>
<script type='text/javascript' charset='utf-8'>
function ajax(m,u,p,c,o){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
};
var params=[];
for( var 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 );
}
function createmenu(r,o,h){
o.menu.innerHTML=r;
}
function bindEvents(){
var oSelItem=document.querySelector('select[name="item1"]');
var oSelService=document.querySelector('select[name="service1"]');
oSelItem.onchange=function(e){
var method='post';
var url=location.href;
var params={
'action':'get_dependant_menu',
'id':this.options[ this.options.selectedIndex ].value
};
var opts={
menu:oSelService
};
ajax.call( this, method, url, params, createmenu, opts );
}.bind( oSelItem );
}
document.addEventListener( 'DOMContentLoaded', bindEvents,false );
</script>
<style type='text/css' charset='utf-8'>
select {padding:1rem;width:300px;}
</style>
</head>
<body>
<h1>Chained select menus using basic ajax</h1>
<form method='post'>
<select name='item1' class='country'>
<?php
$sql='select * from `item` order by `sr` asc;';
$stmt=$user_home->runQuery( $sql );
$stmt->execute();
if( $stmt->rowCount() > 0 ){
while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
echo "<option value='{$row['IRN']}'>{$row['Name']}";
}
}
?>
</select>
<select name='service1' class='country'>
</select>
</form>
</body>
</html>
使用Add Row
按钮添加新行时,bindEvents
函数中上面注册的onchange事件处理程序将不会使用新添加的选择菜单进行克隆。确保任何&amp;所有新添加的选择菜单都使用相同的机制(即:ajax),然后最容易实现的解决方案是将inline event handlers
分配给item
下拉菜单。上面的javascript可以更改为(未测试btw)
<script type='text/javascript' charset='utf-8'>
/* AJAX FUNCTION */
function ajax(m,u,p,c,o){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
};
var params=[];
for( var 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 );
}
/* AJAX CALLBACK */
function createmenu(r,o,h){
o.menu.innerHTML=r;
}
/* INLINE EVENT HANDLER */
function evtselect(e){
try{
var el=e.target;
/* it is NOT necessary to have the `action` parameter... that was for testing for me initially */
var params={
'action':'get_dependant_menu',
'id':el.value
};
/*
newly added nodes ( add row ) should have their names changed*/
so the following line needs attention! Basically you need to find, in the DOM,
the next select menu on the same row ( think parentNode, nextSibling etc etc )
The following is NOT tested......!!!!!
*/
var td=el.parentNode.nextSibling;
var opts={
menu:td.querySelector('select')
};
ajax.call( this, method, url, params, createmenu, opts );
}catch( err ){
console.log( err );
}
}
</script>
要使用您通常会执行的inline event handler
:
<select name='item' onchange='evtselect(event)'>/* options */</select>