我正在尝试进行三个选择,根据前一个选择的输入显示不同的选项。他们都从 MySQL 查询中获得选项。
第一个选择始终相同且从不变化,第二个选择应该检查第一个选择中提供的答案,然后显示相应的答案,第三个选择应该做同样的事情,听第二个选择。
到目前为止,我已经创建了以下代码:
<?php
$res = CommonFunctions::returnPrimario();
foreach($res as $dato){
echo '<option value = "' .$dato. '">' . ucwords($dato) .'</option>';
}
?>
</select>
<select name = "secundario" id = "secundario">
<?php
$res = CommonFunctions::returnSecundario();
foreach($res as $dato){
echo '<option value = "' .$dato. '">' . ucwords($dato) .'</option>';
}
?>
</select>
<select name = "nombre" id = "nombre">
<?php
$res = CommonFunctions::returnEjercicio();
foreach($res as $dato){
echo '<option value = "' .$dato. '">' . ucwords($dato) .'</option>';
}
?>
</select>
我们将非常感谢您提供的任何帮助。
提前谢谢您。
最佳答案
您需要使用 JavaScript 在选择下拉列表中放置一个监听器。 “onchange”事件将是合适的,例如
var primario = document.getElementById("primario");
// add event listener to the <select> tag
primario.addEventListener("change", function(){
// function to determine the second dropdown
});
在确定第二个和第三个下拉列表时,您可以使用 ajax 到您的服务器,例如
primario.addEventListener("change", function(){
var http = new XMLHttpRequest();
var url = "yourpage.com/target/page";
// send value of the first dropdown list
var params = "primarioValue=" + this.value;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
//Call a function when the state changes.
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// Change the list of second dropdown
// provided your response is already wrap it in appropriate <option> tag
document.getElementById("secundario").innerHTML = http.responseText;
}
}
http.send(params);
});
对第二个下拉菜单执行相同的操作。
另一种选择是将所有选项存储在 javascript (JSON) 中并在事件监听器中运行过滤逻辑
我可以建议您使用 jQuery 来简化您的流程(但不要依赖它)。
希望对你有帮助!
关于javascript - 三个HTML选择哪些选项依赖于前面的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33962460/