[英]dynamic drop down box?
I got a database table called category as shown: 我得到了一个名为category的数据库表,如下所示:
I am trying to do a dynamic drop down box and the index script is shown as: 我正在尝试做一个动态下拉框,索引脚本显示为:
<?php
try {
$objDb = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `category`
WHERE `master` = 0";
$statement = $objDb->query($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'There was a problem';
}
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Dependable dropdown menu</title>
<meta name="description" content="Dependable dropdown menu" />
<meta name="keywords" content="Dependable dropdown menu" />
<link href="/css/core.css" rel="stylesheet" type="text/css" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="/js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="/js/core.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<form action="" method="post">
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update"
disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update"
disabled="disabled">
<option value="">----</option>
</select>
</form>
</div>
</body>
</html>
The update.php is shown as: update.php显示为:
<?php
if (!empty($_GET['id']) && !empty($_GET['value'])) {
$id = $_GET['id'];
$value = $_GET['value'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `category`
WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array('<option value="">Select one</option>');
foreach($list as $row) {
$out[] = '<option
value="'.$row['id'].'">'.$row['name'].'</option>';
}
echo json_encode(array('error' => false, 'list' => implode('',
$out)));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
The 2nd drop down box is not showing the values dependent on the 1st drop down box as shown: 第二个下拉框未显示取决于第一个下拉框的值,如下所示:
Can someone help me please. 有谁可以帮助我吗。
Here is an example that will do what you want. 这是一个可以满足您需求的示例。 Essentially, you can use jQuery / AJAX to accomplish this. 本质上,您可以使用jQuery / AJAX来完成此任务。
I updated my example code to match your server login / table / field names, so if you copy/paste these two examples into files (call them tester.php
and another_php_file.php
) then you should have a fully working example to play with. 我更新了示例代码以匹配您的服务器登录名/表/字段名称,因此,如果将这两个示例复制/粘贴到文件中(分别称为tester.php
和another_php_file.php
),那么您应该有一个可以正常使用的示例。
I modified my example below to create a second drop-down box, populated with the values found. 我在下面的示例中进行了修改,以创建第二个下拉框,其中填充了找到的值。 If you follow the logic line by line, you will see it is actually quite simple. 如果逐行遵循逻辑,您会发现它实际上非常简单。 I left in several commented lines that, if uncommented (one at a time) will show you what the script is doing at each stage. 我留下了几行注释行,如果不加注释(一次注释一遍),则会向您显示脚本在每个阶段的功能。
FILE 1 -- TESTER.PHP 文件1-TESTER.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//alert('Document is ready');
$('#stSelect').change(function() {
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "another_php_file.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#LaDIV').html(whatigot);
$('#theButton').click(function() {
alert('You clicked the button');
});
} //END success fn
}); //END $.ajax
}); //END dropdown change event
}); //END document.ready
</script>
</head>
<body>
<select name="students" id="stSelect">
<option value="">Please Select</option>
<option value="John">John Doe</option>
<option value="Mike">Mike Williams</option>
<option value="Chris">Chris Edwards</option>
</select>
<div id="LaDIV"></div>
</body>
</html>
FILE 2 - another_php_file.php 文件2-another_php_file.php
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
$server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
$login = 'root';
$pword = '';
$dbname = 'test';
mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
mysql_select_db($dbname) or die($connect_error);
//Get value posted in by ajax
$selStudent = $_POST['theOption'];
//die('You sent: ' . $selStudent);
//Run DB query
$query = "SELECT * FROM `category` WHERE `master` = 0";
$result = mysql_query($query) or die('Fn another_php_file.php ERROR: ' . mysql_error());
$num_rows_returned = mysql_num_rows($result);
//die('Query returned ' . $num_rows_returned . ' rows.');
//Prepare response html markup
$r = '
<h1>Found in Database:</h1>
<select>
';
//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
if ($num_rows_returned > 0) {
while ($row = mysql_fetch_assoc($result)) {
$r = $r . '<option value="' .$row['id']. '">' . $row['name'] . '</option>';
}
} else {
$r = '<p>No student by that name on staff</p>';
}
//Add this extra button for fun
$r = $r . '</select><button id="theButton">Click Me</button>';
//The response echoed below will be inserted into the
echo $r;
To answer your question in the comment: "How do you make the 2nd drop down box populate fields that are only relevant to a selected option from the 1st drop down box?" 要在评论中回答您的问题:“您如何使第二个下拉框填充仅与第一个下拉框中的所选选项相关的字段?”
A. Inside the .change
event for the first dropdown, you read the value of the first dropdown box: .change
在第一个下拉列表的.change
事件中,您将读取第一个下拉框的值:
$('#dropdown_id').change(function() {
var dd1 = $('#dropdown_id').val();
}
B. In your AJAX code for the above .change()
event, you include that variable in the data you are sending to the 2nd .PHP file (in our case, "another_php_file.php") B.在上述.change()
事件的AJAX代码中,将该变量包含在要发送到第二个.PHP文件的数据中(在本例中为“ another_php_file.php”)
C. You use that passed-in variable in your mysql query, thereby limiting your results. C.在mysql查询中使用该传入变量,从而限制了结果。 These results are then passed back to the AJAX function and you can access them in the success:
portion of the AJAX function 然后将这些结果传递回AJAX函数,您可以success:
访问它们success:
AJAX函数的一部分
D. In that success function, you inject code into the DOM with the revised SELECT values. D.在该成功函数中,您使用修改后的SELECT值将代码注入DOM。
That is what I am doing in the example posted above: 这就是我在上面发布的示例中所做的:
The user chooses a student name, which fires the jQuery .change()
selector 用户选择一个学生姓名,这将触发jQuery .change()
选择器
Here is the line where it grabs the option selected by the user: 这是它抓住用户选择的选项的行:
var sel_stud = $(this).val();
This value is sent to another_php_file.php
, via this line of the AJAX code: 该值通过AJAX代码的以下行发送到another_php_file.php
:
data: 'theOption=' + sel_stud,
The receiving file another_php_file.php
receives the user's selection here: 接收文件another_php_file.php
在此处接收用户的选择:
$selStudent = $_POST['theOption'];
Var $selStudent (the user's selection posted in via AJAX) is used in the mysql search: Var $ selStudent(通过AJAX发布的用户选择)用于mysql搜索:
$query = " SELECT * FROM `category` WHERE `master` = 0 AND `name` = '$selStudent' "; $ query =“ SELECT * FROM`category`在哪里`master` = 0 AND`name` ='$ selStudent'”;
(When changing the example to suit your database, the reference to $selStudent was removed. But this (here, above) is how you would use it). (在更改示例以适合您的数据库时,已删除对$ selStudent的引用。但这(此处,在上面)是您将如何使用它)。
We now build a new <SELECT>
code block, storing the HTML in a variable called $r
. 现在,我们构建一个新的<SELECT>
代码块,将HTML存储在名为$r
的变量中。 When the HTML is fully built, I return the customized code back to the AJAX routine simply by echoing it back: 完全构建HTML之后,我只需将其回显即可将自定义代码返回给AJAX例程:
echo $r;
The received data (the customized <SELECT>
code block) is available to us inside the AJAX success: function() {//code block}
, and I can inject it into the DOM here: 接收到的数据(自定义的<SELECT>
代码块)可以在AJAX success: function() {//code block}
内部使用success: function() {//code block}
,我可以在此处将其注入到DOM中:
$('#LaDIV').html(whatigot);
And voila, you now see a second dropdown control customized with values specific to the choice from the first dropdown control. 瞧,现在您将看到第二个下拉控件,其中自定义了第一个下拉控件中的特定选择的值。
Works like a non-Microsoft browser. 像非Microsoft浏览器一样工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.