我有一个“项目”表,如下所示
Project_ID | Client_ID
---------------------------
P1 C1
P2 C1
P3 C2
P4 C2
P5 C3
P6 C3
我有一个选择id=“1”显示所有客户端 ID。
我正在展示另一个选择id=“2”显示分配给客户端 ID 的所有项目。
基本上我想展示option值选择id=“2”基于从中选择的值选择id=“1”.
例如,如果有人选择
<option value="C3">C3</option>
那么下面应该有
<select id="2">
<option value="P5">P5</option>
<option value="P6">P6</option>
</select>
我认为 Ajax 是答案,但我不知道正确的方法。
您可以为选择框的 onChange 事件添加事件侦听器。
在更改事件上,获取选择框的值,并使用 ajax 请求将其值发送到服务器,并根据第一个选择框的值获取要在第二个选择框中显示的值,并将其显示在第二个选择框中。
基于国家选择的州选择示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Populate City Dropdown Using jQuery Ajax</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "process-request.php",
data: { country : selectedCountry }
}).done(function(data){
$("#response").html(data);
});
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td>
<label>Country:</label>
<select class="country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
</select>
</td>
<td id="response">
<!--Response will be inserted here-->
</td>
</tr>
</table>
</form>
</body>
</html>
Backend:
<?php
if(isset($_POST["country"])){
// Capture selected country
$country = $_POST["country"];
// Define country and city array
$countryArr = array(
"usa" => array("New Yourk", "Los Angeles", "California"),
"india" => array("Mumbai", "New Delhi", "Bangalore"),
"uk" => array("London", "Manchester", "Liverpool")
);
// Display city dropdown based on country name
if($country !== 'Select'){
echo "<label>City:</label>";
echo "<select>";
foreach($countryArr[$country] as $value){
echo "<option>". $value . "</option>";
}
echo "</select>";
}
}
?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)